您的位置:首页 > 移动开发

Win32程序启动时的头几个消息

2008-12-01 14:24 239 查看
用C语言撰写的Win32程序中,会见到如下的标准代码段:

     hwnd = CreateWindow (szAppName,                  // window class name
                      TEXT ("The Hello Program"), // window caption
                      WS_OVERLAPPEDWINDOW,        // window style
                      CW_USEDEFAULT,              // initial x position
                      CW_USEDEFAULT,              // initial y position
                      CW_USEDEFAULT,              // initial x size
                      CW_USEDEFAULT,              // initial y size
                      NULL,                       // parent window handle
                      NULL,                       // window menu handle
                      hInstance,                  // program instance handle
                      NULL) ;                     // creation parameters
    
     ShowWindow (hwnd, iCmdShow) ;
     UpdateWindow (hwnd) ;
    
     while (GetMessage (&msg, NULL, 0, 0))
     {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }
     return msg.wParam ;

我以前常常疑惑,不知道窗口创建时的消息是怎样流动的。

消息队列的解释

今天重新看书(《深入浅出MFC》和《Programming Windows》),才较为彻底的了解了,程序有两个消息队列,见《深入浅出MFC》第一章P72:
    "如果把應用程式獲得的各種「輸入」分類,可以分為由硬體裝置所產生的訊息(如滑鼠    移動或鍵盤被按下),放在系統佇列(system queue)中,以及由Windows 系統或其它    Windows 程式傳送過來的訊息,放在程式佇列(application queue)中。以應用程式的眼光來看,訊息就是訊息,來自哪裡或放在哪裡其實並沒有太大區別,反正程式呼叫GetMessage API 就取得一個訊息,程式的生命靠它來推動。所有的GUI 系統,包括UNIX的X Window 以及OS/2 的Presentation Manager,都像這樣,是以訊息為基礎的事件驅動系統。"

收到的第一个消息WM_CREATE

不会进入消息队列,而是由CreateWindow直接调用WndProc,见《Programming Windows》第三章中的说明:

"The very first message that a window procedure receives—and the first that HELLOWIN's WndProc chooses to process—is WM_CREATE. WndProc receives this message while Windows is processing the CreateWindow function in WinMain. That is, when HELLOWIN calls CreateWindow, Windows does what it has to do and, in the process, Windows calls WndProc with the first argument set to the window handle and the second argument set to WM_CREATE (the value 1). WndProc processes the WM_CREATE message and returns controls back to Windows. Windows can then return to HELLOWIN from the CreateWindow call to continue further progress in WinMain. "

窗口的显示与重绘

关于这个问题,《Programming Windows》第三章中也已经说得很明白了,就是CreateWindow只负责创建窗口,而显示窗口的工作就落在了ShowWindow这个函数上。那UpdateWindow又用来干嘛的呢?因为窗口被创建后,整个客户区都是无效的(invalid),ShowWindow也只是会用刷出个背景,而UpdateWindow就是用来产生WM_PAINT消息的,这个消息进不进消息队列呢?答案是不进消息队列。这个我们在MSDN上查找UpdateWindow函数的说明便可以知道。《Programming Window》中关于这一段解释的原文如下:

"How does a client area become invalid? When the window is first created, the entire client area is invalid because the program has not yet drawn anything on the window. The first WM_PAINT message (which normally occurs when the program calls UpdateWindow in WinMain) directs the window procedure to draw something on the client area. "
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息