DWORD CreateThread(PVOID pArg)
{
CreateWnd();
return 0;
}
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
g_hInst = hInstance;
HANDLE hThrd = CreateThread(NULL,0,CreateThread,NULL,0,NULL);
CloseHandle(hThrd);
//The message loop
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
我们似乎什么都没见到,只是窗口一闪,啥都没了.因为g_hWnd为全局变量,我们的理智告诉我们,在主线程没有退出之前,g_hWnd是不会销毁的.而用断点调试,将会发现在WndProc函数中只能接收WM_CREATE及以后一些消息,之后的再也收不到了,特别是WM_PAINT似乎就凭空消失了!那么,代码什么都没变更,只是移动到了分线程中,为何会出现这个问题呢? [Page]
一切似乎很简单,在MSDN中我们找到了答案(原文见:http://support.microsoft.com/kb/90975/en-us):
In a multithreaded application, any thread can call the CreateWindow() API to create a window. There are no restrictions on which thread(s) can create windows.
It is important to note that the message loop and window procedure for the window must be in the thread that created the window. If a different thread creates the window, the window won’t get messages from DispatchMessage(), but will get messages from other sources. Therefore, the window will appear but won’t show activation or repaint, cannot be moved, won’t receive mouse messages, and so on.
该段话大意是:窗口在任何线程中都可以创建,但消息循环必须要和创建窗口在同一线程,否则窗口将无法从DispatchMessage()获取任何消息!
原来如此,最重要是这么一句:It is important to note that the message loop and window procedure for the window must be in the thread that created the window.
好吧,那么我们在支线程中放置消息循环代码,看看是什么结果吧:
#include \"windows.h\"
HWND g_hWnd = NULL;
HINSTANCE g_hInst;
LRESULT WndProc(HWND hWnd,UINT wMsg,WPARA