在纠结多线程、回调、win32 api函数等麻烦事的同时,我收到了一个idea event。(呵呵)
如果我没有定义全局(或在设计类时为静态)回调函数,而是在注册窗口类时分配DefWindowProc
了 for lpfnWndProc
,然后在单独的线程上运行整个事件循环,该怎么办?
这样我就不必在类中实现回调this
时解决问题,
并且主线程的执行继续,将你从那个被上帝抛弃的 while 循环中解放出来,让你做任何事情,甚至打开另一个窗口(耶!)
“正常”方式:
LRESULT CALLBACK WndProc(...)
{
... // process event information
return DefWindowProc(...);
}
int CALLBACK WinMain(...)
{
... // initialize whatever needs initializing :)
WNDCLASSEX wc;
...
wc.lpfnWndProc = WndProc;
... // register the class, create the window, etc...
MSG msg;
while(GetMessage(&msg, 0, 0, 0) != 0)
{
... // TranslateMessage(&msg) if you want/need it
DispatchMessage(&msg); // dispatches the message to WndProc
}
return static_cast<int>(msg.wParam);
}
我新发现的很棒的方式:
DWORD WINAPI MyAwesomeEventLoop(void* data) // must be static in a class
{
... // do whatever you need with the data
MSG msg;
while(GetMessage(&msg, 0, 0, 0) != 0)
{
... // TranslateMessage(&msg) if you want/need it
... // process event information
// call PostQuitMessage(0) to leave the loop
}
return static_cast<DWORD>(msg.wParam);
}
int CALLBACK WndProc(...)
{
...
WNDCLASSEX wc;
...
wc.lpfnWndProc = DefWindowProc;
...
HANDLE threadHandle = 0;
// use "this" as the 4th parameter when implementing in a class
threadHandle = CreateThread(0, 0, MyAwesomeEventLoop, 0, 0, 0);
... // you are now free to do whatever you want! :)
// waits untill the thread finishes
// hopefully because PostQuitMessage(0) was called
WaitForSingleObject(threadHandle, INFINITE);
DWORD returnValue = 0;
GetExitCodeThread(threadHandle, &returnValue);
CloseHandle(threadHandle);
...
return static_cast<int>(returnValue);
}
你们有什么感想?