gpt4 book ai didi

c++在新线程中创建窗口

转载 作者:行者123 更新时间:2023-11-30 04:17:17 28 4
gpt4 key购买 nike

我有一个基本的窗口程序,问题是当我尝试在消息循环已经启动后在新线程中创建窗口时窗口显示一秒钟然后消失。有没有人没有这个原因?可以在单独的线程中创建窗口吗?

     int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
{
::hInstance =hInstance; // initialize global variables
::nCmdShow =nCmdShow;

// start thread
HANDLE threadHandle = startThread(StartUp);

MSG msg;
while(GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
::CloseHandle(threadHandle);

return static_cast<int>(msg.wParam);
}

DWORD WINAPI StartUp(LPVOID lpParam) // new thread runs here
{
//code to create a new window...

}

到目前为止我发现如果当前线程中没有窗口,GetMessage(&msg, 0, 0, 0) 返回 false ...如何解决这个问题?

最佳答案

如果没有窗口,

GetMessage() 不会返回 FALSE。它只是在调用线程的消息队列中寻找消息。您正在为其 hWnd 参数指定 NULL,因此它不会关心消息如何排队,无论是通过 PostMessage() 到窗口,还是通过 PostThreadMessage() 到线程的 ID。

每个线程都有自己的本地消息队列,因此需要自己的消息循环。在主线程开始其消息循环后,您当然可以在工作线程中创建一个新窗口。它们彼此独立。因此,无论您在主线程中遇到什么问题,都与在工作线程中创建窗口无关。其他事情正在发生。

话虽如此,请记住 GetMessage() 返回一个 BOOL,它实际上是一个 int,而不是一个真正的 bool GetMessage() 可以返回 3 不同返回值之一:

  1. -1如果发生错误
  2. 0 如果检索到 WM_QUIT 消息
  3. >0如果检索到任何其他消息

您只检查 0 和 != 0,因此如果 GetMessage() 错误返回 -1,则您将其视为成功而不是失败。甚至 MSDN 也说不要这样做:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms644936.aspx

Because the return value can be nonzero, zero, or -1, avoid code like this:

while (GetMessage( lpMsg, hWnd, 0, 0)) ...

The possibility of a -1 return value means that such code can lead to fatal application errors. Instead, use code like this:

BOOL bRet;

while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

关于c++在新线程中创建窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17202377/

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