Now we need to review the message mechanism of the system and window:
A program has one or more threads. The system has a thread Queue (a linked list) to manage all these threads and create a message queue for each thread.
When a message is generated (for example, a window is clicked), the system places the message in the message queue of the window and waits for the window to process it.
The window should always be on standby, ready to retrieve and process messages from the thread queue!
To retrieve a message from a message queue, the getmessage function is generally used. To retrieve a message at any time, a cycle is required. For example:
while(GetMessage(Msg, 0, 0, 0)) dobegin ...end;
How can I retrieve a message? Use the dispatchmessage function to send the message to the (previously mentioned) window callback function, which is generally like this:
While (getmessage (MSG, 0, 0, 0) dobegin translatemessage (MSG ); {some keyboard messages need to use the translatemessage function and send more specific keyboard messages required by the system} dispatchmessage (MSG); end;
If the getmessage function does not return 0, the message loop is an endless loop. When can the getmessage function return 0?
0 is returned only when getmessage receives the wm_quit message.
When necessary, we can use the postquitmessage function in the callback function to send a wm_quit message to the thread message queue to close the thread.
The parameter of the postquitmessage function is the exit code for the application. 0 in postquitmessage (0) is the exit code we specify. It serves as the wparam parameter of the wm_quit message. For example:
function WndProc(wnd: HWND; msg: UINT; wParam: Integer; lParam: Integer): Integer; stdcall;begin Result := 0; if msg = WM_DESTROY then PostQuitMessage(0) else Result := DefWindowProc(wnd, msg, wParam, lParam);end;