Joke Collection Website - Public benefit messages - WINDOWS message processing process
WINDOWS message processing process
1. Introduction
2. The concept of Windows message mechanism
1. The difference between DOS and Windows driver mechanisms
2. Message
3. Source of messages
4. Composition of Windows message system
5. Response to messages
3. Windows messages Key points of the mechanism
1. Window procedure
2 Message type
3 Message Queues (Message Queues)
4 Queue messages and non-queue messages Message
5 Windows message functions
6 Message Deadlocks
7 BroadcastSystemMessage
4. MFC message mechanism
1. Under the MFC framework, the process of receiving and processing messages from Windows
2. MFC internal message processing method
1. Introduction
In C In the article Program Architecture, we saw that a program is composed of several layers and modules. So, how do you transfer information between these modules and between your program and Windows? On the Windows platform, how is information transferred? The windows message mechanism is responsible for this, which is the core part of Windows.
Messages include data and instructions.
2. The concept of Windows message mechanism
1. The difference between DOS and Windows driver mechanisms
1) DOS is process driven.
Traditional MS-DOS programs are mainly sequential. A relational, process-driven approach to programming. A process is a combination of a predefined sequence of operations, which has a certain beginning, middle, and end. The program directly controls the sequence of program events and procedures. This kind of programming method is program-oriented rather than user-oriented, has poor interactivity, and the user interface is not friendly enough because it forces users to work according to a certain unchangeable mode. Its basic model is shown in Figure 1.1.
2) Windows is event (message) driven
Event-driven programming is a brand-new programming method. It is not controlled by the sequence of events, but by the sequence of events. The occurrence of such events is random, uncertain, and has no predetermined order. This allows program users to arrange the program flow in various reasonable orders. For applications that require user interaction, event-driven programming has advantages that cannot be replaced by process-driven methods. It is a user-oriented programming method. In addition to completing the required functions during the programming process, it also considers various possible inputs from the user and designs corresponding processing procedures. It is a "passive" programming method. When the program starts running, it is in a state of waiting for the user to input an event, then obtains the event and responds accordingly, and then returns after processing and is in a state of waiting for the event. Its block diagram is shown in Figure 1.2:
2. Messages
The Windows system is an event-driven OS. The occurrence of every event will generate a message, and we know it through the message. What happened, understand the incident, and then solve the incident. What is news? It is difficult to give a definition, so let’s explain it from different aspects:
1) The composition of the message: A message consists of a message name (UINT) and two parameters (WPARAM, LPARAM). When the user makes input or the status of the window changes, the system will send a message to a certain window.
For example, when the menu is transferred, a WM_COMMAND message will be sent. The high word of WPARAM (HIWORD(wParam)) is the ID number of the command, which is the menu ID for the menu. Of course, users can also define their own message names, or use custom messages to send notifications and transfer data.
2) Who will receive the message: A message must be received by a window. In the window process (WNDPROC), you can analyze the messages and process the messages that you are interested in. For example, if you want to process menu selections, you can define the code to process WM_COMMAND. If you want to perform graphic output in the window, you must process WM_PAINT.
3) Where do the unprocessed messages go: M$ writes a default window procedure for the window. This window procedure will be responsible for processing those messages that you do not process. It is precisely because of this default window procedure that we can use Windows windows for development without having to pay too much attention to the processing of various messages in the window. For example, a lot of messages will be sent when the window is dragged, but we can ignore them and let the system handle them by itself.
4) Window handle: When talking about messages, we cannot but talk about window handles. The system uses window handles to uniquely identify a window in the entire system. When sending a message, a window handle must be specified to indicate which window the message is from. Window reception. Each window will have its own window procedure, so user input will be processed correctly. For example, if there are two windows using one window procedure code, when you click the mouse on window one, the message will be sent to window one instead of window two through the handle of window one.
3. Source of messages
Event-driven events revolve around the generation and processing of messages. A message is a message about an event that occurred. Event-driven is implemented by the message loop mechanism. It can also be understood that a message is a notification reporting the occurrence of an event.
There are four message sources for Windows applications:
1) Input messages: including keyboard and mouse input. This type of message is first placed in the system message queue, and then Windows sends them to the application message queue, and the application processes the message.
2) Control message: used for two-way communication with Windows control objects, such as list boxes, buttons, check boxes, etc. This message is emitted when the user changes the current selection in a list box or changes the state of a check box. This type of message generally does not go through the application message queue, but is sent directly to the control object.
3) System messages: Respond to programmed events or system clock interrupts. Some system messages, such as DDE messages (Dynamic Data Exchange messages), go through the Windows system message queue, while some are sent directly to the application's message queue without going through the system message queue, such as creating window messages.
4) User message: This is defined by the programmer himself and actively issued in the application, and is generally processed internally by a certain part of the application.
4. Composition of the Windows message system
The Windows message system consists of the following three parts:
Message queue: Windows can maintain it for all applications A message queue, the application must get the message from the message queue and then dispatch it to a form.
Message loop: Through this loop mechanism, the application retrieves a message from the message queue, dispatches it to the appropriate window, and then continues to retrieve the next message from the message queue and dispatches it to the appropriate window. , proceed in sequence.
Window procedure: Each window has a window procedure to receive messages passed by Windows to the window. The task of the window procedure is to obtain the message and respond to it. The window procedure is a callback function that usually returns a value to Windows after processing a message.
5. Message response
Messages are generated from system events (including timer events) and user events. Windows uses messages to load and close (and other processing, For example, drawing a window, etc.) application, a typical performance is that during the shutdown operation, Windows sends a shutdown message to all running applications, telling them to exit the memory. At this time, the application responds to the OS by responding to the message. , therefore, messages are the means for applications to interact with WinOS..
The steps from message generation to response by the window: (as shown below)
1gt; The system has occurred or the user has issued a certain message. event.
2gt; Windows translates this event into a message, and then puts it in the message queue.
3gt; The application receives this message from the message queue and stores it in TMsg Recording.
4gt; The application passes the message to an appropriate form procedure.
The form procedure responds to this message and processes it. The message is passed to the form function of this form.
3. Key points of Windows message mechanism
1. Window procedure
Each window will have a callback function (WndProc) called the window procedure, which brings There are four parameters, namely: window handle (Window Handle), message ID (Message ID), and two message parameters (wParam, lParam). When the window receives a message, the system will call this window procedure to process the message. (So ??it’s called a callback function)
2 Message types
1) System-Defined Messages
Messages defined in advance in the SDK, Non-user defined, its range is between [0×0000, 0×03ff], and can be divided into the following three categories:
Window Message (Windows Message)
With the window Related to internal operations, such as creating windows, drawing windows, destroying windows, etc. It can be a general window, a Dialog, a control, etc.
For example: WM_CREATE, WM_PAINT, WM_MOUSEMOVE, WM_CTLCOLOR, WM_HSCROLL..
Command Message (Command Message)
Related to processing user requests, such as clicking a menu command message is generated when an item or toolbar or control is selected.
WM_COMMAND, LOWORD(wParam) represents the ID of the menu item, toolbar button or control. If it is a control, HIWORD(wParam) represents the control message type
Control notification (Notify Message)
Control notification message, which is the most flexible message format, its Message, wParam, lParam They are: WM_NOTIFY, control ID, pointer to NMHDR. NMHDR contains the content of control notifications and can be expanded arbitrarily.
2) Application-Defined Messages
User-defined messages have the following provisions for their scope:
WM_USER: 0×0400 -0×7FFF (ex. WM_USER 10)
WM_APP(winvergt; 4.0): 0×8000-0xBFFF (ex.WM_APP 4)
RegisterWindowMessage: 0xC000-0xFFFF
3 Message Queues
There are two types of message queues in Windows
1) System Message Queue
This is a unique Queue in the system. The device driver (mouse, keyboard) will convert the operation input into a message and store it in the system queue. Then the system will put the message into the message queue of the thread where the target window is located (thread-specific message queue). )
2) Thread-specific Message Queue
Each GUI thread will maintain such a thread message queue. (This queue is only created when a thread calls a GDI function, and is not created by default). Then the messages in the thread message queue will be sent to the corresponding window procedure (WndProc) for processing.
Note: WM_PAINT and WM_TIMER in the thread message queue will only be processed when there are no other messages in the Queue. WM_PAINT messages are also merged to improve efficiency. All other messages are processed in a first-in-first-out (FIFO) manner.
4 Queued Messages and Non-Queued Messages
1) Queued Messages
The message will be saved first In the message queue, the message loop will fetch messages from this queue and distribute them to each window for processing
such as mouse and keyboard messages.
2) NonQueued Messages
Messages will bypass the system message queue and thread message queue and be sent directly to the window process for processing
For example: WM_ACTIVATE, WM_SETFOCUS, WM_SETCURSOR, WM_WINDOWPOSCHANGED
Note: The message sent by postMessage is a queue message, which will post the message to the message queue; the message sent by SendMessage is a non-queue message, which is directly sent to the window procedure for processing
5 Windows message functions
1) PostMessage (PostThreadMessage), SendMessage
PostMessage: Put the message into the thread message queue where the specified window is located and return immediately. PostThreadMessage: Returns immediately after placing the message in the message queue of the specified thread.
SendMessage: Send the message directly to the window procedure for processing, and return only after the processing is completed.
2) GetMessage, PeekMessage
PeekMessage will return immediately and the message can be retained
GetMessage will delete the message if it returns when there is a message
3 ) TranslateMessage, TranslateAccelerator
TranslateMessage: Convert a virtual-key message into a character message (character message), and put it in the message queue of the current thread, and the message loop will take it out for processing next time.
TranslateAccelerator: Map shortcut keys to corresponding menu commands. It will convert WM_KEYDOWN or WM_SYSKEYDOWN into the corresponding WM_COMMAND or WM_SYSCOMMAND message in the shortcut key table, and then send the converted WM_COMMAND or WM_SYSCOMMAND directly to the window procedure for processing, and will return after processing.
6 Message Deadlocks
Assume there are threads A and B, now there are the following steps
1) Thread A SendMessage to thread B, A Wait for the message to be processed in thread B and then return
2) Thread B receives the message from thread A and processes it. During the processing, B also SendMessgae to thread A, and then waits for the return from A. .
Because at this time, thread A is waiting to return from thread B and cannot process the message sent by B, which leads to threads A and B waiting for each other, forming a deadlock. Multiple threads can also form a circular deadlock.
You can use SendNotifyMessage or SendMessageTimeout to avoid deadlock.
7 BroadcastSystemMessage
The messages we generally come into contact with are sent to the window. In fact, the receiver of the message can be diverse, and it can be applications. ), installable drivers, network drivers, system-level device drivers, etc.
BroadcastSystemMessage is an API that can send messages to the above system components.
So how are these messages transmitted? Let's take MFC as an example to look at the message transmission process.
4. MFC message mechanism
In the main function of a Windows application, you must first register the window class, and then create and display the window. After creating the window, the program enters the message loop. In the message loop, the program continuously obtains messages and dispatches the messages to the corresponding window function for processing.
We can see that under the framework of MFC, the header files of classes that can perform message processing will contain the DECLARE_MESSAGE_MAP() macro, which mainly performs message mapping and message processing. The declaration of the handler function
. The implementation files of classes that can perform message processing generally contain the following structure.
BEGIN_MESSAGE_MAP(CInheritClass, CBaseClass) //{{AFX_MSG_MAP(CInheritClass)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
Here we mainly implement the message mapping and message processing functions.
All classes that can perform message processing are based on the CCmdTarget class, which means that the CCmdTarget class is the parent class of all classes that can perform message processing. The CCmdTarget class is the foundation and core of MFC processing command messages.
At the same time, MFC defines the following two main structures:
AFX_MSGMAP_ENTRY
struct AFX_MSGMAP_ENTRY
{//"""//
};
and AFX_MSGMAP
struct AFX_MSGMAP
{//""``//
};
The AFX_MSGMAP_ENTRY structure contains all relevant information of a message, and AFX_MSGMAP has two main functions. One: used to obtain the message mapping entry address of the base class. Two: Get your own message mapping entry address.
In fact, MFC fills all messages into the AFX_MSGMAP_ENTRY structure one by one, forming an array that stores all messages and their related message parameters. At the same time, the first address of the array can be obtained through AFX_MSGMAP, and the message mapping entry address of the base class can also be obtained. This is an example of calling the message response of its base class when it does not respond to the message.
Now let’s analyze how MFC allows the window procedure to process messages. In fact, all MFC window classes intercept messages through the hook function _AfxCbtFilterHook, and set the window procedure in the hook function _AfxCbtFilterHook. for AfxWndProc. The original window procedure is stored in the member variable m_pfnSuper
1. Under the MFC framework, the process of receiving and processing messages from Windows:
2. MFC internal message processing method
MFC receives a posted message:
The only significant difference between MFC processing a posted and sending a message is that the posted message spends some time in the application's message queue. It remains in the queue until the message pump pops it. Here's how to accept a sent message. The message pump in the MFC application is in the member function Run() of CWinApp. When the application starts running, Run() is called, and Run() divides the time into two parts. One part is used to perform background processing, such as canceling the temporary CWnd object; the other part is used to check the message queue. When a new message comes in, Run() extracts it—that is, uses GetMessage() to remove the message from the queue, runs the two message translation functions PreTranslateMessage() and TranslateMessage(), and then calls the DispatchMessage() function. The window process to which the message is intended. As shown below.
We use an instance function A to send a message to function B to take a look at the internal message processing process of MFC.
1. First, function A should obtain the pointer of the CWnd class object of the message, and then call the member function SendMessage() of CWnd.
LRESULT Res=pWnd-gt; SendMessage(UINT Msg, WPARAM wParam, LPARAM lParam);
The pWnd pointer points to the target CWnd class object. The variable Msg is the message, and the wParam and lParam variables contain the parameters of the message, such as where the mouse clicked or what menu item was selected. The message result returned by the target window is placed in the variable Res.
To send a message to a window without a CWnd function object, you can directly call the Windows API using the handle of the following target window:
LRESULT Res=::SendMessage(HWND hWnd, UINT Msg , WPARAM wParam, LPARAM lParam);
The hWnd here is the handle of the target window.
If it is asynchronous transmission, you can also use PostMessage(). The message is the same as above, but the return value Res is different. Res is not a value returned by the target form, but a Boolean value used to represent the message. Whether it was successfully put into the message queue.
2. Under normal circumstances, once the message is sent, the application background will automatically send it, but in special circumstances, you need to delete a message yourself, for example, if you want to receive it in the application Stop the application before some kind of message. There are two ways to delete a message from the application message queue, but neither of these methods involves MFC.
The first method: peek into the message queue to see if a message is there without interfering with anything.
BOOL res=::PeekMessage(LPMSG lpMsg, HWND hWnd, UINT wMsFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg);
The second method: actually waits until a Until a new message arrives on the queue, the message is then deleted and returned.
BOOL res=::GetMessage(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax);
In these two methods, the variable hWnd specifies the window to intercept the message, If this variable is set to NULL, all window messages will be intercepted. The wMsgFilterMin and wMsgFilterMax variables correspond to the variable Msg in SendMessage() and specify the range of the message to be viewed. If "0, 0" is used, all messages will be intercepted. If WM_KEYFIRST, WM_KEYLAST or WM_MOUSEFIRST, WM_MOUSELAST is used, all keyboard or mouse messages will be intercepted. The wRemoveMsg variable specifies whether PeekMessage() should actually be removed from the queue (GetMessage() always deletes the message). This variable can take two values:
PM_REMOVE, PeekMessage() will delete the message.
PM_NOREMOVE() ) will leave the message in the queue and return a copy of it. Of course, if you leave the message in the message queue and then call PeekMessage() again to view the same type of message, it will return exactly. The same message.
The lpMsg variable is a pointer to the MSG structure that contains the retrieved message.
typedef struct tagMSG {
HWND hwnd; // window handle message is intended for
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time; // the time the message was put in the queue
POINT pt; // the location of the mouse cursor when the
// message was put in the queue
} MSG;
3. The message will be put in the message queue. CwinApp's member function Run divides the time into two parts when the application is running. One part performs background processing, and the other part checks the message queue. When a new message is found, Run calls GetMessage() to retrieve the message from the queue. to retrieve the message.
3. Run the two message translation functions PreTranslateMessage() and ::TranslateMessage() for translation. Mainly find the location of the function object, the action identifier of the message and the execution operations related to the message.
4. Use the DispatchMessage() function to call the expected function B process of the message and execute it.
- Previous article:I just started dating a girl. Should I call and text every day?
- Next article:How to send an Apple phone by SMS?
- Related articles
- I received a strange text message saying that my mother was dead.
- I didn't order a cake, but I received the news of ordering a cake.
- The latest news of the epidemic situation in Shishou City, Hubei Province 2022 (the latest situation of the epidemic situation in Shishou City)
- Introduction of Prepaid 58 yuan Low Consumption Package?
- Introduction to the functions of the new Huawei watch watch3pro
- Ado has three dumb.
- How is Guizhou Xunhao legal affairs?
- How to recover blocked messages?
- Have Wu Qingfeng and Zhang Xuan ever been together?
- How to Eliminate Maintenance Skills of BMW X3