Windows message Mechanism Essentials

Source: Internet
Author: User
Tags case statement

1. Window procedure
Each window will have a callback function called a window procedure (WndProc) with four parameters, namely: Window handle (Windows Handle), message ID, and two message parameters (WParam, LParam), This window procedure is called by the system to process the message when the window receives the message. (so called callback function)

2 message Types
1) System Definition message (system-defined Messages)
Pre-defined messages in the SDK, which are not user-defined, range between [0x0000, 0x03ff] and can be divided into the following three categories:
1> window messages (Windows message)
Related to the internal workings of the window, such as creating Windows, drawing windows, destroying windows, etc. It can be a normal window, a dialog, a control, and so on.
such as: Wm_create, WM_PAINT, Wm_mousemove, Wm_ctlcolor, Wm_hscroll ...
2> Command Message
A command message is generated when a user request is processed, such as when a menu item or toolbar or control is clicked.
WM_COMMAND, LoWord (WParam) represents the ID of a menu item, toolbar button, or control. If it is a control, HiWord (WParam) represents the control message type
3> Control Notification (Notify Message)
The control notifies the message, which is the most flexible message format, with its messages, WParam, LPARAM, respectively: WM_NOTIFY, control ID, pointer to NMHDR. NMHDR contains the contents of the control notification and can be arbitrarily extended.
2) Program definition message (application-defined Messages)
User-defined messages have the following provisions for their scope:
Wm_user:0x0400-0x7fff (ex. wm_user+10)
Wm_app (winver> 4.0): 0x8000-0xbfff (ex. WM_APP+4)
Registerwindowmessage:0xc000-0xffff

3 Message Queuing (msg Queues)  
There are two types of Message Queuing in Windows  
1) system Message Queuing (Systems message queue)  
This is a system-unique Queue, device-driven (mouse, Keyboard) Converts the operation input into a message that exists in the system queue, which is then placed in the message queue of the thread on which the target window is located (thread-specific message queues) waiting to be processed  
2" thread Message Queuing (thread-specific message queue)  
Each GUI thread maintains such a thread message queue. (This queue is created only when the thread calls the GDI function and is not created by default). The messages in the thread message queue are then sent to the appropriate window procedure (WNDPROC) for processing.  
Note: Thread Message Queuing Wm_paint,wm_timer is processed only if there are no other messages in the queue wm_ Paint messages are also merged to improve efficiency. All other messages are processed in first-in, in-and-out (FIFO) mode.

4 Queue messages (Queued Messages) and non-queue messages (non-queued Messages)
1) Queue message (Queued Messages)
Messages are saved in the message queue, and the message loop takes messages from this queue and distributes them to each window processing
such as mouse, keyboard messages.
2) Non-queue messages (nonqueued Messages)
Messages that bypass system Message Queuing and thread Message Queuing are sent directly to the window process are processed
such as: Wm_activate, Wm_setfocus, Wm_setcursor, wm_windowposchanged
Note: The message sent by PostMessage is a queue message that posts the message to the message queue; SendMessage sends a message that is not a queue message, and is sent directly to the window procedure processing

5 PostMessage (postthreadmessage), SendMessage
PostMessage: Returns the message immediately after it is placed in the thread message queue where the specified window is located. PostThreadMessage: Returns the message immediately after it is placed in the message queue of the specified thread.
SendMessage: The message is sent directly to the window process processing, the process is finished before returning.

6 GetMessage, PeekMessage
PeekMessage will return immediately to keep the message
GetMessage returns a message when there is a message

7 TranslateMessage, TranslateAccelerator
TranslateMessage: Converts a virtual-key message into a character message (character message) and puts it into the message queue of the current thread, and the next fetch of the message loop.
TranslateAccelerator: The shortcut key corresponds to the corresponding menu command. It transforms the Wm_keydown or wm_syskeydown into the corresponding WM_COMMAND or Wm_syscommand message in the accelerator table, and then sends the converted WM_COMMAND or Wm_syscommand directly to the window process, It will not be returned until the processing is finished.

8 (Message deadlock (msg deadlocks)
Assuming the threads A and B, now have the following steps
1) thread A sendmessage to thread B, a waits for the message to be returned after process B is processed
2) thread B receives a message from thread A and processes it, B also sendmessgae to thread a during processing, and waits for a return from a.
Because at this point, thread A is waiting to be returned from thread B, unable to process the message from B, which causes the thread A, b to wait for each other to form a deadlock. Multiple threads can also form ring deadlocks.
You can use SendNotifyMessage or sendmessagetimeout to avoid deadlocks.

9 Broadcastsystemmessage
We generally contact the message is sent to the window, in fact, the recipient of the message can be a variety of, it can be an application (applications), can install the driver (installable drivers), network equipment (networks drivers), System-Level device drivers (System-level devices drivers), etc.,
Broadcastsystemmessage This API can send messages to the above system components.

First, Introduction
As the Windows operating system continues to evolve, many software development packages offer the ability to develop Windows-based application software. Although these development packages are not the same, popular with Visual C + +, visual Basic, Delphi, C + + Builder, and so on, but the software developed by these different languages is one thing is the same-run on the Windows operating platform, Must accept the Windows operating mechanism. The message mechanism for the soul of the Windows operating system will inevitably be accepted by many applications running under Windows operating systems developed in different languages. Therefore, in order to write in-depth Windows programs, you must have a good understanding of the operating mechanism of Windows. The following article will be a more in-depth analysis of the message running mechanism under the Windows operating system.
ii. Windows Event-driven mechanism
Many of us use VC, Delphi and so on as the development of language programmers are step by step from the DOS Basic, C + + come over, and mostly in the beginning of learning programming is also first from the DOS programming environment, so in the habit of DOS under the process-driven form of sequential programming method , it is often impossible to adapt to the event-driven approach taken by windows in the process of transforming to a development environment under Windows. Because DOS and windows are operating in a very different way, any program under DOS is a sequential, process-driven program design approach. This program has an obvious beginning, a clear process, and an obvious end, so the program can control the whole sequence of events or processes directly. Even when dealing with exceptions, the process is still a sequential, process-driven structure. and the drive of Windows is event-driven, that is, the process of the program is not controlled by the order of events, but by the occurrence of events to control, all events are unordered, a programmer, when writing a program, do not know the user will first press which button, do not know the program first trigger which message. So our main task is to sort and manage the messages that are being developed by the application to be sent or received. Event-driven programming is carried out closely around the generation and processing of messages, and a message is about the event that occurs.
iii. message loops for Windows
The Windows operating system maintains a message queue for each running application. When an event occurs, Windows does not send the firing event directly to the application, but instead translates it into a Windows message before adding the message to the application's message queue. Applications need to receive these messages through a message loop. In MFC, a class library that is well encapsulated for WINAPI is used, although it is possible to provide programming with an object-oriented interface that enables Windows programmers to program in a face-like object, giving programmers the most tedious parts of the SDK programming to focus on the implementation of the functionality. However, due to the introduction of good encapsulation features, we can not directly manipulate some of the core code. The looping and receiving of messages is simply represented by a message map similar to the following:
Begin_message_map (Ctemmsview, CFormView)
{{Afx_msg_map (Ctemmsview)
On_wm_lbuttondown ()
On_command (Id_opendata, Onopendata)
On_wm_timer ()
On_wm_paint ()
}} Afx_msg_map
End_message_map ()
While the message map described above is very concise and convenient to process messages during programming, it is clear that it is difficult to understand how the message participates in looping and distributing. It is therefore necessary to explore the specifics of how it works through the SDK (software Developers kit, Software Development Toolkit) code that is deep into the core of Windows programming that is encapsulated by MFC. In SDK programming, you typically add code that processes message loops in the entry point WinMain function of a Windows application to retrieve messages sent by Windows, and then WinMain to assign the messages to the appropriate window functions and process them:
......
MSG msg; Define Message Name
while (GetMessage (& msg, NULL, 0, 0))
{
TranslateMessage (& msg); Translating messages
DispatchMessage (& msg); Withdraw the news.
}
return msg.wparam;
Although simple but the key code for all Windows programs, with the task of acquiring, interpreting, and distributing messages, the following focuses on the analysis of its function and function:
The MSG structure is defined in the header file as follows:
typedef struct TAGMSG
{
HWND hwnd;
UINT message;
WPARAM WPARAM;
LPARAM LPARAM;
DWORD time;
Point pt;
} MSG, *pmsg;
The specific meaning of its data members is as follows:
HWND: The handle of the window to which the message is to be sent, using this parameter to decide which window to receive the message.
Message: The number of messages that uniquely identifies a message type. Each message type is predefined in Windows files.
WParam: A 32-bit message parameter, the exact meaning of this value depends on the message itself.
LParam: Ibid.
Time: When the message is placed in the message queue, the time value that is written in the domain is not the date, but the measured values from the start of Windows. Windows with
This domain is used to keep messages in the correct order.
PT: Mouse coordinates when messages are placed in Message Queuing.
The message loop begins with the GetMessage call, which extracts a message from the message queue. The function's four parameters can get the message in a controlled manner, the first parameter specifies the address of the MSG structure to receive the message, the second parameter represents the window handle, which is generally set to NULL, indicating that you want to get the message for all windows created by the application; the third to fourth parameter is used to specify the message range. The next three parameters are set to the default values to receive all messages sent to any one of the windows that belong to the application. GetMessage () returns TRUE after receiving any message except Wm_quit, if GetMessage receives a WM_QUIT message, returns false to exit the message loop, terminating the program run. Therefore, the message loop with GetMessage () can be cycled until the Wm_quit is received. When a message other than Wm_quit is read in GetMessage, it is first interpreted by the function translatemessage (), but it does not work for most messages. The key function here is the DispatchMessage () function, which passes the Windows message obtained by GetMessage to the window procedure specified in the MSG structure for the window. After the message handler finishes processing the message, the code loops back to the beginning to receive another message, completing a complete message loop.
Because the Windows operating system is a non-stripped multi-tasking operating system. Windows can give control to other applications only after the application has voluntarily surrendered CPU control. In the message loop, it is necessary to have a system function that can hand over the control to realize the cooperative multi-task operation. Only the three functions of GetMessage, PeekMessage, and WaitMessage can be completed, and other tasks cannot be performed if one of the three functions is not called in the application. The GetMessage function automatically surrenders control when it cannot find a message waiting for the application to process, and Windows takes control of the CPU to other applications waiting to gain control. Because any Windows application contains a message loop, this implicit surrender of control guarantees the merging of individual applications to share control. Once the message destined for the application arrives at the application queue, the next statement of the GetMessage statement starts executing. A message loop that uses the GetMessage function waits when there is no message in the message queue, and can take time-consuming operations such as I/O port operations, if needed, but requires the use of the PeekMessage function in the message loop instead of the getmessage. The method of using PeekMessage is similar to GetMessage, and here is a typical example of a message loop using the PeekMessage function:
MSG msg;
BOOL Bdone=false;
do{
if (PeekMessage (& Msg,null,0,0,pm_remove)) {
if (msg.message==wm_quit)
Bdone=true;
else{
TranslateMessage (& msg);
DispatchMessage (& msg);
}
}
No message processing for long-time operation
else{
...//long-time operation
}
} while (!bdone)
......
The PeekMessage function returns immediately regardless of whether there is a message in the application message queue, and if you want to wait for a new message to be queued, you can use a function waitmessage with no return value to peekmessage the message loop.
Iv. Handling of WINDOWDS messages
window procedure processing messages usually start with a switch statement, with a case statement for each message ID that it handles, which is functionally similar to the message map of MFC:
Switch (umsgid)
{
Case Wm_timer:
Process for Wm_timer timer messages
return 0;
Case WM_LBUTTONDOWN:
The process of wm_ Lbuttondown the left mouse button click Message
Ruturn 0;
......
Default
Other messages are handled by this default handler function.
return DefWindowProc (Hwnd,umsgid,wparam,lparam);
}
It is important to return 0 after processing the message, otherwise Windows will continue to retry. For messages that are not ready to be processed in the program, the window procedure throws them to DefWindowProc for default processing, and returns the return value of that function. In the message delivery hierarchy, you can think of the DefWindowProc function as the topmost function. This function emits a wm_syscommand message that is used by the system to perform various common operations that are common to most windows in the window environment, such as updating the body title of the window, and so on. Under MFC, you can use some of the following code to implement the same functionality as the SDK code above:
Begin_message_map (Ctemmsview, CFormView)
{{Afx_msg_map (Ctemmsview)
On_wm_lbuttondown ()
On_wm_timer ()
}} Afx_msg_map
End_message_map ()
Summary: The Windows environment provides a very rich system resource, which can be developed to meet a variety of target functions of the application system. In order to go deep into Windows programming, we must first have a good understanding of the operating mechanism of Windows system, and this article only focuses on an important operational mechanism of Windows--the message mechanism. It is helpful to cultivate the idea of programming under Windows. You can refer to the "SDK Reference" section of the MSDN Online Help for a detailed discussion of some of the related issues.

Windows message Mechanism Essentials

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.