windows程序设计 消息循环

来源:互联网 发布:华为手机游戏数据 编辑:程序博客网 时间:2024/05/01 10:50

The Message Loop

A programretrieves these messages from the message queue by executing a block of codeknown as the "message loop":

while (GetMessage (&msg, NULL, 0,0))

{

TranslateMessage (&msg) ;

DispatchMessage (&msg) ;

}

Themsgvariable is a structure of type MSG, which is defined in the WINUSER.Hheader file like this:

typedef struct tagMSG

{

HWND hwnd ;

UINT message ;

WPARAM wParam ;

LPARAM lParam ;

DWORD time ;

POINT pt ;

}

MSG, * PMSG ;

The POINTdata type is yet another structure, defined in the WINDEF.H header file likethis:

typedef struct tagPOINT

{

LONG x ;

LONG y ;

}

POINT, * PPOINT;

TheGetMessagecall that begins the message loop retrieves a message from themessage queue:

GetMessage (&msg, NULL, 0, 0)

This callpasses to Windows a pointer to a MSG structure named msg. The second, third,and fourth arguments

are set toNULL or 0 to indicate that the program wants all messages for all windowscreated by the program.

Windowsfills in the fields of the message structure with the next message from themessage queue. The fields of

thisstructure are:

hwnd Thehandle to the window which the message is directed to. In the HELLOWIN program,this is thesame as the hwndvalue returned from CreateWindow, because that's theonly window the program has.

message Themessage identifier. This is a number that identifies the message. For eachmessage, there is a corresponding identifier defined in the Windows headerfiles (most of them in WINUSER.H) that begins with the identifier WM("window message"). For example, if you position the mouse pointerover HELLOWIN's client area and press the left mouse button, Windows will put amessage in the message queue with a messagefield equal to WM_LBUTTONDOWN, whichis the value 0x0201.

wParam A32-bit "message parameter," the meaning and value of which depend onthe particular message.

lParamAnother 32-bit message parameter dependent on the message. time  The time the message was placed in themessage queue.

If themessagefield of the message retrieved from the message queue is anything exceptWM_QUIT (which equals 0x0012), GetMessagereturns a nonzero value. A WM_QUITmessage causes GetMessageto return 0.

Thestatement:

TranslateMessage (&msg) ;

passes themsgstructure back to Windows for some keyboard translation. (I'll discuss thismore in Chapter 6.)

Thestatement

DispatchMessage (&msg) ;

again passesthe msgstructure back to Windows. Windows then sends the message to theappropriate window procedure for processing. What this means is that Windowscalls the window procedure. In HELLOWIN, the window procedure is WndProc. AfterWndProcprocesses the message, it returns control to Windows, which is still servicingthe DispatchMessagecall. When Windows returns to HELLOWIN following theDispatchMessagecall, the message loop continues with the next GetMessagecall.

0 0