GetMessage用法错误导致程序不能退出
2011-09-27 22:53 捣乱小子 阅读(1638) 评论(0) 编辑 收藏 举报#include <windows.h> #include <stdio.h> LRESULT CALLBACK WinUoowProc( //回调函数声明 HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); int WINAPI WinMain( HINSTANCE hInstance, //WinMain主函数 HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { 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=WinUoowProc; wndcls.lpszClassName="First Window"; wndcls.lpszMenuName=NULL; wndcls.style=CS_DBLCLKS |CS_HREDRAW | CS_VREDRAW; RegisterClass(&wndcls); //注册窗口 HWND hwnd; //创建窗口 hwnd=CreateWindow("First Window","Window BY Dancer_dus7",WS_OVERLAPPEDWINDOW, 300,200,600,400,NULL,NULL,hInstance,NULL); ShowWindow(hwnd,SW_SHOWNORMAL); //显示窗口 UpdateWindow(hwnd); //更新窗口 MSG msg; while(GetMessage(&msg,NULL/*hwnd*/,0,0)) //主循环 注意若注释处改成hwnd,则程序仍运行在任务管理器 { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } LRESULT CALLBACK WinUoowProc( //回调函数 HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch(uMsg) //消息处理 { case WM_CHAR: char szChar[20]; sprintf(szChar,"char is %d",wParam); MessageBox(hwnd,szChar,"key code:",0); break; case WM_LBUTTONDOWN: MessageBox(hwnd,"mouse clicked!","mouse",MB_OK); HDC hdc; hdc=GetDC(hwnd); TextOut(hdc,0,50,"HELLO WORLD!",strlen("HELLO WORLD!")); ReleaseDC(hwnd,hdc); break; case WM_PAINT: HDC hDC; PAINTSTRUCT ps; hDC=BeginPaint(hwnd,&ps); TextOut(hDC,0,0,"First Window!",strlen("First Window!")); EndPaint(hwnd,&ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd,uMsg,wParam,lParam); } return 0; }MSDN中的说明,要避免while(GetMessage( lpMsg, hWnd, 0, 0))这种用法,避免出现-1的结果,窗口已经销毁,但是仍在运行。
Note that the function return value can be nonzero, zero, or -1. Thus, you should avoid code like this:
(GetMessage( lpMsg, hWnd, 0, 0))...
The possibility of a -1 return value means that such code can lead to fatal application errors.
while(GetMessage( lpMsg, NULL, 0, 0))才正确。
但是觉得还是没有说清楚,就是为什么GetMessage第二个参数为hwnd的时候就会出现窗口销毁而程序仍在任务管理窗口运行的现象,msdn好像没有说的很明白?望高手解答。
更多请访问:http://daoluan.net