问题描述
我有一个应用程序的第二个线程调用 GetMessage()
在循环中。在某些时候,第一个线程意识到用户想要退出应用程序并通知第二个线程它应该终止。由于第二个线程停留在 GetMessage()
上,程序从不退出。有没有办法等待有超时的消息?
$ p $ <$> b $ b
第二个线程运行该代码片段:
while(!m_quit&& GetMessage ; msg,NULL,0,0))
{
TranslateMessage(& msg);
DispatchMessage(& msg);
}
第一个线程设置 m_quit
to true。
最简单的方法是调用 UINT_PTR timerId = SetTimer NULL,1000,NULL)
,然后调用 GetMessage
。它将每秒向调用线程发送 WM_TIMER
消息,因此 GetMessage
将立即返回。然后,调用 KillTimer(NULL,timerId)
即可取消。
UPDATE 代码:
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; //暂停!你可以调用SetLastError()或某事...
return TRUE;
}
I have an application which second thread calls GetMessage()
in a loop. At some point the first thread realizes that the user wants to quit the application and notifies the second thread that it should terminate. As the second thread is stuck on GetMessage()
, the program never quits. Is there a way to wait for messages with a timeout?I’m open to other ideas too.
EDIT: (additional explanations)
The second thread runs that snippet of code:
while ( !m_quit && GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
The first thread sets m_quit
to true.
The easiest way is to just call UINT_PTR timerId=SetTimer(NULL, NULL, 1000, NULL)
before calling GetMessage
. It will post a WM_TIMER
message to the calling thread every second, so the GetMessage
will return promptly. Then, call KillTimer(NULL, timerId)
to cancel it.
UPDATE Sample code:
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;
}
这篇关于GetMessage超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!