笔者在日常开发中用到一种场景,该场景是启动一个子线程,在该线程里循环查找指定窗口是否存在。

里面用到了EnumWindowsGetClassNameGetWindowText的API。

从而引发了一个线程无法正常退出,使用WaitForSingleObject等待线程结束将永远无法结束的问题。

初步猜测可能是因为EnumWindows的回调函数中使用了GetClassNameGetWindowText的原因。这两个函数会给消息循环发消息,最后造成的阻塞问题。

这里贴出解决该问题的代码,当然此类问题最好使用其他的解决方案去规避。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void XXXXX::WaitXXXXXThread()
{
MSG msg;
BOOL bQuit = FALSE;

while (!bQuit)
{
DWORD dwRet = MsgWaitForMultipleObjects(1, &m_tThread, FALSE, INFINITE, QS_ALLINPUT);
if (dwRet == WAIT_OBJECT_0 + 1)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
bQuit = TRUE;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else if (dwRet == WAIT_OBJECT_0)
{
break;
}
else
{
dwRet = GetLastError();
return;
}
}
}