我们先来看一个简单的程序:
#include <iostream> #include <windows.h> using namespace std; void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime ) { cout << "hello" << endl; } int main() { SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc); while(1); return 0; }我们预期程序会每秒打印一次hello, 但有点奇怪, 程序没有打印hello, 也就是说, myTimerProc没有被调用。 了解Windows消息机制的朋友们可能会知道上面程序的问题, 因此我们打算修改为:
#include <iostream> #include <windows.h> using namespace std; void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime ) { cout << "hello" << endl; } int main() { MSG msg; SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc); while(GetMessage(&msg,NULL,NULL,NULL)) { if (msg.message == WM_TIMER) { TranslateMessage(&msg); DispatchMessage(&msg); } } while(1); return 0; }这样就好了, 程序每秒打印一次hello world. 但是, 这样的话, 主线程就没法做其他事情了, 只能在循环进行消息处理, 那该怎么办呢? 搞个线程试试, 如下:
#include <iostream> #include <windows.h> using namespace std; void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime ) { cout << "hello xxx" << endl; } DWORD WINAPI ThreadFun(LPVOID pM) { MSG msg; while(GetMessage(&msg,NULL,NULL,NULL)) { if (msg.message == WM_TIMER) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } int main() { SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc); HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL); CloseHandle(handle); while(1) { cout << "world yyyyyy" << endl; Sleep(500); } return 0; }略微意外的是, 让然没有hello xxx的打印, 且看继续修改的代码:
#include <iostream> #include <windows.h> using namespace std; void myTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime ) { cout << "hello xxx" << endl; } DWORD WINAPI ThreadFun(LPVOID pM) { MSG msg; SetTimer(NULL, 1, 1000, (TIMERPROC)myTimerProc); while(GetMessage(&msg,NULL,NULL,NULL)) { if (msg.message == WM_TIMER) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; } int main() { HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL); CloseHandle(handle); while(1) { cout << "world yyyyyy" << endl; Sleep(500); } return 0; }现在好了, 既有hello xxx, 又有world yyyyyy
最后要说明的是, 上述程序有可能会出现线程不同步的问题, 导致打印的结果可能有误。