gpt4 book ai didi

c++ - 应用程序退出时线程无法退出 - C++

转载 作者:行者123 更新时间:2023-11-30 03:09:10 26 4
gpt4 key购买 nike

我的应用程序创建了一个轮询 Windows 消息的线程。当需要关闭时,我的应用程序会发送 WM_QUIT 消息。

在应用程序线程中,这就是我尝试关闭事物的方式:

if ( _hNotifyWindowThread != NULL )
{
ASSERT(_pobjNotifyWindow != NULL);

::SendMessage( _pobjNotifyWindow->m_hWnd, WM_QUIT, 0, 0 );
::WaitForSingleObject( _hNotifyWindowThread, 50000L );
::CloseHandle( _hNotifyWindowThread ); // <-- PC never gets here.
_hNotifyWindowThread = NULL;
}

这是在我的线程函数中运行的消息泵:

// Start the message pump...
while ( (bRetVal = ::GetMessage(
&msg, // message structure
_pobjNotifyWindow->m_hWnd, // handle to window whose messages are to be retrieved
WM_DEVICECHANGE, // lowest message value to retrieve
WM_DEVICECHANGE // highest message value to retrieve
)) != 0 )
{
switch ( bRetVal )
{
case -1: // Error generated in GetMessage.
TRACE(_T("NotifyWindowThreadFn : Failed to get notify window message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
return ::GetLastError();
break;

default: // Other message received.
::TranslateMessage( &msg );
::DispatchMessage( &msg );
break;
}
}

delete _pobjNotifyWindow; // Delete the notify window.

return msg.wParam; // Return exit code.

Microsoft documentation for GetMessage状态:

If the function retrieves the WM_QUIT message, the return value is zero.

Note that GetMessage always retrieves WM_QUIT messages, no matter which values you specify for wMsgFilterMin and wMsgFilterMax.

如果是这种情况,那么我希望对检索 WM_QUIT 消息的 GetMessage 的调用返回 0。但是,调试让我相信该消息未正确接收。奇怪的是,我可以在 WndProc 函数中放置一个断点,它似乎得到了 WM_QUIT 消息。

我做错了什么?我应该使用不同的函数在线程之间发布消息吗?谢谢。

最佳答案

这是完整的答案(我几乎可以肯定):

替换

::SendMessage( _pobjNotifyWindow->m_hWnd, WM_QUIT, 0, 0 ); 

::PostMessage( _pobjNotifyWindow->m_hWnd, WM_CLOSE, 0, 0 ); 

替换

 ( (bRetVal = ::GetMessage( &msg, _pobjNotifyWindow->m_hWnd, WM_DEVICECHANGE, WM_DEVICECHANGE )) != 0 ) 

使用 ( (bRetVal =::GetMessage( &msg, NULL ,0 ,0 )) != 0 )

在你的 WindowsProcedure 中:

 case WM_CLOSE : DestroyWindow( hWnd ); break; //can be return 

case WM_DESTROY : PostQuitMessage( 0 );

关于c++ - 应用程序退出时线程无法退出 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4330027/

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