我有一个很旧的申请表,我很惊讶。此应用程序运行时没有消息循环。
(获取消息或查看消息)。
怎么可能?
从Visual Studio编辑的示例:
HINSTANCE g_hInstance = NULL;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow);
ATOM _RegisterClass(HINSTANCE hInstance);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
_RegisterClass(hInstance);
InitInstance(hInstance, SW_NORMAL);
return 0;
}
ATOM _RegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXA wcex = {0};
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_SAVEBITS;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = "TEST_CLASS";
ATOM a = 0;
a = RegisterClassExA(&wcex);
return a;
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
g_hInstance = hInstance; // Store instance handle in our global variable
hWnd = CreateWindowA("TEST_CLASS", "TEST_WINDOW", WS_OVERLAPPEDWINDOW,
0, 0, 0, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
SendMessageW(hWnd, WM_USER, 111, 0);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_CREATE:
OutputDebugStringA("Create called.\n");
break;
case WM_USER:
{
if (wParam == 111)
{
OutputDebugStringA("User called.\n");
}
}
break;
case WM_DESTROY:
OutputDebugStringA("Destroy called.\n");
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
调试输出:
创建调用。
用户调用。
毁灭召唤。
程序“[2152]test.exe:native”已退出,代码为0(0x0)。
最佳答案
这是预期的行为。CreateWindow
调用SendMessage
将WM_NCCREATE
和WM_CREATE
发送到正在创建的窗口。SendMessage
的行为如下(引用msdn):
如果指定的窗口是由调用线程创建的,则窗口过程将立即作为子例程调用。
程序调用CreateWindow
,随后调用窗口过程(在WM_CREATE
时输出“create called”),然后返回。它验证窗口句柄是否为非空(事实就是这样),并返回退出代码0,而不是输入消息泵。
它不会输出“destroy called”(如您所料),因为这不会发生。窗口没有被破坏(好吧,最终,它被操作系统破坏了),程序只是退出。
关于编辑的代码:
新代码在调用SendMessageW
时有所不同,后者再次直接调用窗口过程。因此,虽然没有消息泵,但是接收到用户消息。
现在看来,销毁信息也通过了,这确实有点令人惊讶。不知道这是什么原因。
注意,窗口是用一个“a”函数创建的,所以通常不建议调用“w”函数(尽管在这里它看起来是“工作的”)。