gpt4 book ai didi

c++ - GetMessage 超时

转载 作者:IT老高 更新时间:2023-10-28 22:23:39 28 4
gpt4 key购买 nike

我有一个应用程序,第二个线程在循环中调用 GetMessage()。在某些时候,第一个线程意识到用户想要退出应用程序并通知第二个线程它应该终止。由于第二个线程卡在 GetMessage() 上,因此程序永远不会退出。有没有办法等待超时消息?我也对其他想法持开放态度。

编辑:(附加说明)

第二个线程运行这段代码:

while ( !m_quit && GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}

第一个线程将 m_quit 设置为 true。

最佳答案

最简单的方法是在调用 GetMessage 之前调用 UINT_PTR timerId=SetTimer(NULL, NULL, 1000, NULL)。它会每秒向调用线程发送一条 WM_TIMER 消息,因此 GetMessage 会及时返回。然后,调用 KillTimer(NULL, timerId) 取消它。

更新示例代码:

BOOL GetMessageWithTimeout(MSG *msg, UINT to)
{
BOOL res;
UINT_PTR timerId = SetTimer(NULL, NULL, to, NULL);
res = GetMessage(msg);
KillTimer(NULL, timerId);
if (!res)
return FALSE;
if (msg->message == WM_TIMER && msg->hwnd == NULL && msg->wParam == timerId)
return FALSE; //TIMEOUT! You could call SetLastError() or something...
return TRUE;
}

关于c++ - GetMessage 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866311/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com