思考一种不同的方式来运行win32事件循环没有WndProc
Thoughts on a different way to running a win32 event loop without WndProc?
在处理多线程、回调、win32 api函数和其他麻烦的时候,我收到了一个想法事件。(哈哈)
如果,而不是定义一个全局(或静态设计类时)回调函数,而不是分配DefWindowProc
为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);
}
你们觉得怎么样?
GetMessage docs on MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644936 (v = vs.85) . aspx
阅读第一句话:"从调用线程的消息队列中检索消息。"
窗口的消息队列绑定到创建它的线程。由于您在主线程上创建了窗口,因此在新线程上运行的事件循环将不会接收该窗口的任何消息。如果您想在另一个线程上运行事件循环,则需要先创建线程,然后在该线程上创建窗口。
这并没有真正为您带来任何东西,只是现在您在通用事件循环中拥有了特定于窗口类的事件处理代码,这非常丑陋。如果需要后台工作,请使用工作线程。将GUI和事件反应器保留在主线程中,并按照文档使用回调。
如果你有一个类的实例处理窗口,即使在单线程代码中,你也不应该让它们全局化(否则你的将在未来遭受痛苦的重构)。
相关文章:
- C++线程:如何在一个线程仍在运行时阻止另一个线程执行 (Win32)
- C++ DLL 运行时错误"abc.dll is not a valid WIN32 application" 。请帮助解决这个问题
- Win32 函数可以在同一线程上异步运行吗?
- 如何检查 win32 exe 文件是否已运行?(使用 win32 API 代码)
- 如何在 Linux/Apache 虚拟主机上运行 win32 控制台应用程序?
- Exe不是有效的win32应用程序,但在64位上运行
- 是否可以在Windows 8环境上在Visual Studio 2005上运行VC ,Win32应用程序
- Win32 控制台代码在哪里运行?从多个线程使用时控制台挂起
- 如何将任何 *.jpg图像嵌入Win32可执行文件中并在运行时使用它
- 使用文件I/O正确创建和运行win32服务
- C++Win32 在低优先级模式下运行应用程序/线程
- CMake:运行链接命令时出错:%1不是有效的Win32应用程序
- 运行时的 win32 控件
- 什么可能导致我的 C++ win32 应用程序在后台运行
- OpenSSL 在作为 win32 服务运行时SSL_CTX_new崩溃
- 从支持/clr的win32 C++运行C#
- WinXP上具有C运行库libs 2011的Win32程序无效
- 如何防止Win32应用程序在主窗口关闭后在后台运行
- Win32 应用程序在启动时不运行
- c++ WIN32:运行没有命令提示符窗口的程序