C++ c++;在新线程中创建窗口
我有一个基本的窗口程序,问题是当我试图在一个新线程中创建一个窗口时,在消息循环已经启动之后,窗口会显示一秒钟并消失。有人不知道原因吗?可以在单独的线程中创建窗口吗C++ c++;在新线程中创建窗口,c++,window,C++,Window,我有一个基本的窗口程序,问题是当我试图在一个新线程中创建一个窗口时,在消息循环已经启动之后,窗口会显示一秒钟并消失。有人不知道原因吗?可以在单独的线程中创建窗口吗 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ::hInstance =hInstance; // initialize global
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...
}
int-WINAPI-WinMain(HINSTANCE-HINSTANCE、HINSTANCE-hPrevInstance、LPSTR-lpCmdLine、int-nCmdShow)
{
::hInstance=hInstance;//初始化全局变量
::nCmdShow=nCmdShow;
//起始线程
HANDLE threadHandle=startThread(启动);
味精;
while(GetMessage(&msg,0,0,0))
{
翻译信息(&msg);
发送消息(&msg);
}
::闭合手柄(螺纹手柄);
返回静态_cast(msg.wParam);
}
DWORD WINAPI启动(LPVOID lpParam)//新线程在此运行
{
//创建新窗口的代码。。。
}
到目前为止,我发现如果当前线程中没有窗口,则GetMessage(&msg,0,0,0)
返回false。。。有没有办法在这里转转 GetMessage()
如果没有窗口,则不会返回FALSE。它只在调用线程的消息队列中查找消息。您正在为其hWnd
参数指定NULL
,因此它将不关心消息如何排队,无论是通过PostMessage()
到窗口,还是通过postmreadmessage()
到线程ID
每个线程都有自己的本地消息队列,因此需要自己的消息循环。在主线程启动其消息循环后,您肯定可以在工作线程中创建一个新窗口。它们相互独立。因此,无论您在主线程中遇到什么问题,都与在工作线程中创建窗口无关。还有别的事情
话虽如此,请记住GetMessage()
返回一个BOOL
,它实际上是一个int
,而不是一个真正的BOOL
GetMessage()
可以返回3个不同的返回值之一:
WM\u QUIT
消息GetMessage()
在出错时返回-1,则将其视为成功而不是失败。甚至MSDN也表示不要这样做:
因为返回值可以是非零、零或-1,所以请避免这样的代码:
while (GetMessage( lpMsg, hWnd, 0, 0)) ...
BOOL bRet;
while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
返回值为-1的可能性意味着这样的代码可能导致致命的应用程序错误。相反,请使用如下代码:
while (GetMessage( lpMsg, hWnd, 0, 0)) ...
BOOL bRet;
while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
我创建了一个名为CFrame的类,重点是能够轻松创建一个窗口,而不必处理消息循环。像JavaJavaRe纲中的JFrice类可以抽象细节,但是在消息循环中可以做的事情是不同的。