PostQuitMessage(0);不能退出程序啊?

来源:百度知道 编辑:UC知道 时间:2024/06/01 04:51:35
#include <windows.h>
#include <stdio.h>

LRESULT CALLBACK WinSunProc(
HWND hwnd,
UINT umsg,
WPARAM wParam,
LPARAM lParam
);

int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
)
{
//初始化窗口属性
WNDCLASS wndcls;
wndcls.cbClsExtra = 0;
wndcls.cbWndExtra = 0;
wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndcls.hCursor = LoadCursor(NULL,IDC_CROSS);
wndcls.hIcon = LoadIcon(NULL,IDI_ERROR);
wndcls.hInstance = hInstance;
wndcls.lpfnWndProc = WinSunProc;
wndcls.lpszClassName = "Test";
wndcls.lpszMenuName = NULL;
wndcls.style = CS_HREDRAW | CS_VREDRAW;
//注册窗口类
RegisterClass(&wndcls);
//创建窗口
HWND hwnd;
hwnd = CreateWindow("Test","My First App",WS_OVERLAPPEDWINDOW,0,0,300,400,NULL,NULL,hInstance,NULL);
//产生窗口

应该是while(GetMessage(&msg,0,0,0)) 你对消息进行窗口过滤了。WM_QUIT是直接发给线程的,并没指定窗口,况且这个时候hwnd引用的窗口都没了。

把GetMessage(&msg,hwnd,0,0)改成GetMessage(&msg, NULL, 0, 0);

如果不改, 当窗口被Destroy后, 再调用GetMessage会导致返回值为-1, 成了死循环

参见msdn

If there is an error, the return value is -1. For example, the function fails if hWnd is an invalid window handle or lpMsg is an invalid pointer. To get extended error information, call GetLastError.

Warning 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, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
Dis