none
这段代码运行后为什么程序无法退出? RRS feed

  • 问题

  • #include <Windows.h>

    LRESULT CALLBACK MyWinProc(     
           HWND
           hwnd,
           UINT
           uMsg,
           WPARAM
           wParam,
           LPARAM
           lParam
           );

     

    int WINAPI WinMain(     
           HINSTANCE
           hInstance,
           HINSTANCE
           hPrevInstance,
           LPSTR
           lpCmdLine,
           int
           nCmdShow
           )
    {
     WNDCLASS cls;
     cls.cbClsExtra = 0;
     cls.cbWndExtra = 0;
     cls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
     cls.hCursor = LoadCursor(NULL,IDC_CROSS);
     cls.hIcon = LoadIcon(NULL,IDI_ERROR);
     cls.hInstance = hInstance;
     cls.lpfnWndProc = MyWinProc;
     cls.lpszClassName = "First Class";
     cls.lpszMenuName = NULL;
     cls.style = CS_HREDRAW | CS_VREDRAW;
     
     RegisterClass(&cls);

     HWND hWnd = CreateWindow("First Class","Test",WS_OVERLAPPEDWINDOW,0,100,600,400,NULL,NULL,hInstance,NULL);
     ShowWindow(hWnd,SW_SHOWNORMAL);
     UpdateWindow(hWnd);

     MSG msg;
     while (GetMessage(&msg,hWnd,0,0))
     {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
     }
     return 0;
    }

    LRESULT CALLBACK MyWinProc(     
             HWND
             hwnd,
             UINT
             uMsg,
             WPARAM
             wParam,
             LPARAM
             lParam
             )
    {
     switch (uMsg)
     {
     case WM_CLOSE:
      if (MessageBox(hwnd,"你真的要退出程序吗?","Notification",MB_YESNO) == IDYES)
      {
       DestroyWindow(hwnd);
      }   
      break;

     case WM_DESTROY:
      PostQuitMessage(0);
      break;

     default:
      return DefWindowProc(hwnd,uMsg,wParam,lParam);
     }

     return 0;
    }

    2010年8月14日 9:42

答案

  • 	while (GetMessage(&msg,NULL,0,0))
    	{
    		TranslateMessage(&msg);
    		DispatchMessage(&msg);
    	}
    
    注意这儿,看看MSDN中的说明:
    hWnd
    [in] Handle to the window whose messages are to be retrieved. The window must belong to the calling thread. The following value has a special meaning.
    Value Meaning
    NULL GetMessage retrieves messages for any window that belongs to the calling thread and thread messages posted to the calling thread using the PostThreadMessage function.
    2010年8月14日 12:25