1. 引言
在 C++ 编程,特别是使用 Microsoft Foundation Classes (MFC) 框架进行 Windows 桌面应用开发时,回调函数和事件机制是实现模块解耦、异步处理和消息响应的核心技术。本文将以 Visual Studio 2017 和 Windows 10 为开发环境,详细讲解在 C++/MFC 项目中如何实现这两种功能。
2. 回调函数 (Callback Function) 的实现
回调函数本质是一个通过函数指针调用的函数。你“注册”一个函数,让其在特定条件满足时被系统或另一段代码“回调”。
2.1 使用函数指针
这是 C++ 中最基础的回调实现方式。
// 1. 定义回调函数类型 typedef void (*CallbackFunc)(int, const char*); // 2. 执行某些操作并调用回调的函数 void DoWorkWithCallback(CallbackFunc cb) { // ... 执行一些工作 int result = 42; const char* message = "Operation completed"; // 3. 在适当时机调用回调 if (cb != nullptr) { cb(result, message); } } // 4. 具体的回调函数实现 void MyCallback(int code, const char* msg) { CString str; str.Format(_T("Code: %d, Message: %s"), code, CString(msg)); AfxMessageBox(str); } // 5. 使用示例 void TestFunctionPointer() { // 将 MyCallback 函数指针传递给 DoWorkWithCallback DoWorkWithCallback(MyCallback); }2.2 使用 std::function (C++11 及以上)
std::function更灵活,可以绑定到函数、lambda 表达式、函数对象等。
#include <functional> void ProcessData(const std::vector<int>& data, std::function<void(int)> callback) { for (int value : data) { // 处理每个元素 int processedValue = value * 2; // 调用回调通知处理结果 callback(processedValue); } } void TestStdFunction() { std::vector<int> myData = {1, 2, 3, 4, 5}; // 使用 lambda 表达式作为回调 ProcessData(myData, [](int result) { TRACE(_T("Processed value: %d\n"), result); }); }2.3 MFC 中的典型回调:定时器 (Timer)
MFC 中,通过窗口的WM_TIMER消息实现定时回调是一个经典案例。
// 在窗口类(如 CMyDialog)中 void CMyDialog::OnStartTimer() { // 设置一个定时器,ID 为 1,间隔 1000 毫秒 SetTimer(1, 1000,