Win32 消息循环:使用 GetMessage(&msg, NULL, 0, 0) 关闭窗口后退出?
如果我有下面的代码,如何检测窗口何时关闭,以便我可以退出? r
似乎从未获得值 -1
0
,我需要处理整个线程的消息,不仅仅是当前窗口。
HWND hWnd = CreateWindowExW(0, L"Edit", L"My Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, NULL, NULL);
ShowWindow(hWnd, SW_SHOWDEFAULT);
MSG msg;
BOOL r;
while ((r = GetMessageW(&msg, NULL, 0, 0)) != 0)
{
if (r == -1) { break; }
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
If I have the following code below, how do I detect when the window has been closed, so I can quit? r
never seems to get the value -1
0
, and I need to process messages for the entire thread, not just the current window.
HWND hWnd = CreateWindowExW(0, L"Edit", L"My Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, NULL, NULL);
ShowWindow(hWnd, SW_SHOWDEFAULT);
MSG msg;
BOOL r;
while ((r = GetMessageW(&msg, NULL, 0, 0)) != 0)
{
if (r == -1) { break; }
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
等待
r = -1
并不是检测窗口已关闭的方式。返回值 -1 不是正常情况:它表示消息循环中发生了错误。来自文档:
当
GetMessage
从队列中检索到WM_QUIT
消息时,它将返回值0,并且您应该结束循环。如果您只想知道窗口何时关闭,您可能需要处理
WM_CLOSE
或WM_DESTROY
消息。有关这些消息的讨论,请参阅此问题的答案:Windows 程序中的 WM_QUIT、WM_CLOSE 和 WM_DESTROY 有什么区别?Waiting for
r = -1
is not the way you detect that your window has closed. A return value of -1 is not a normal condition: it indicates that an error has occurred in the message loop.From the documentation:
When
GetMessage
retrieves aWM_QUIT
message from the queue, it will return a value of 0, and you should end the loop.If you just want to know when the window has closed, you probably want to handle either the
WM_CLOSE
orWM_DESTROY
messages. For a discussion of these messages, see the answers to this question: What is the difference between WM_QUIT, WM_CLOSE, and WM_DESTROY in a windows program?我找到了一个解决方案:
WM_NULL
。消息循环可以独立于
WndProc
自行处理问题:根据我的观察:当窗口被销毁时
GetMessage
检索WM_NULL< /code> 消息没有暂停(第一个提示)和
IsWindow
可以检查窗口(确认)。I found a solution for this:
WM_NULL
.The message loop can handle the matter on its own independently of
WndProc
:From my observation: When window is destroyed
GetMessage
retrievesWM_NULL
messages without pause (1st hint) andIsWindow
can check the window (affirmation).