(reproduced) Windows Messaging mechanism

Source: Internet
Author: User

Article Source: Http://www.cnblogs.com/watsonyin/archive/2005/12/12/295536.htmlWindows message mechanism

The most important feature of the Windows operating system is its graphical interface, which is built on the basis of its message processing mechanism. If you do not understand the Windows Messaging mechanism, you will certainly not have a deep understanding of Windows programming. Unfortunately, many programmers are only slightly aware of Windows messages, the use of their knowledge is very little, but also do not know its internal implementation principle, this article tries step by step to disclose I understand the Windows message mechanism. Can say, mastered this part of the knowledge, is to master the Windows programming in the Divine Weapon, flexible use of it, will greatly improve our programming ability.

I. Overview of the message

How do Windows Forms show up on the screen? It is well known that it is implemented through API drawing. The Windows operating system provides a series of API functions for rendering the interface, such as:

²drawtext Drawing Text

²drawedge drawing a border

²drawicon Drawing Icons

²bitblt Drawing bitmaps

²rectangle drawing rectangles

² ...

The complex program interface is implemented through this function.

When do you call these functions? Obviously we need a control center for "giving orders", and we need a command-conveying mechanism to deliver the command to the destination instantly. The control center is a power source, like a heart, that keeps the blood flowing everywhere. This command communication mechanism is the Windows message mechanism, Windows message is like the blood in the body, it is the messenger of command communication.

Windows Message Control Center is typically a three-tier structure, at the top of which is the Windows kernel. The Windows kernel maintains a message queue, and the second-level control center obtains its own messages from this message queue, processes them, some messages are processed directly, and some are sent to the next-level form (Window) or control. The second-level control center is typically the application object for each Windows application. The third-level control center is the Windows Forms object, and each form has a default form procedure that handles the various received messages. As shown in the following:

(Note: Windows refers to Windows operating system; Windows: Windows window; form: includes a window, and a control with a handle; control accusations, which can itself be a window or not; application is the application, Applications may also not use the Windows Messaging mechanism, where we specialize in applications that have message loops)

Figure 1 contains a Windows Most of the content of the mechanism, all of the content described below is actually an interpretation or expansion of the map.

The message is delivered to the application in a fixed structure, as follows:

Public Type MSG

HWND as Long

Message as Long

WParam as Long

LParam as Long

Time as Long

PT as Pointapi

End Type

Where an HWND is a handle to a form, a message is a constant of messages that represents the type of message, wparam and lparam are 32-bit additional information, specifically what content, depending on the type of message, is the time the message was sent, and PT is the location of the mouse where the message was sent.

The following types of messages are included in the Windows operating system:

1. Standard Windows messages:

This kind of news starts with WM_.

2. Notification message

The notification message is a message for standard Windows controls. These controls include buttons, combo boxes (ComboBox), edit boxes (TextBox), list boxes (ListBox), ListView controls, TreeView controls, Toolbars (Toolbar), menus, and so on. Each type of message starts with a different string.

3. Custom Messages

Programmers can also customize messages.

Ii. about Windows handles

Not every control can receive messages, forward messages, and draw itself, only a control with a handle (handle). A control with a handle is essentially a form (window) that can exist independently and can be used as a container for other controls, and a control without a handle, such as a label, cannot exist independently, only as a child control of a window control, which cannot draw itself, but can only be drawn by the parent form.

The essence of a handle is a 32-bit value that is automatically maintained by the system, which is unique at any point in the entire operating system. However, when the handle represents the release of the form, the handle is also freed and the value may be used by other forms. That is, the value of the handle is dynamic, it is itself a unique identity, and the operating system uses a handle to identify and find the object it represents.

However, not all handles are handles to the form, and there are many other types of handles in the Windows system, such as canvas (HDC) handles, brush handles, brush handles, application handles (HINSTANCE), and so on. This handle is not able to receive messages. However, regardless of the handle, it is the unique identifier of the object in the system. This article only discusses form handles.

So why does a handle make a window such a unique feature? The actual reason is because of the message. Because of the handle, the form can receive the message, it will know when to draw their own, draw the child control, know when the mouse clicked on which part of the window, thereby making corresponding processing. The handle is like a person's identity card, with it, you can engage in various social activities, otherwise, you are either a social Heihu, or follow the others, through others to prove your existence.

Third, the transmission of the message

1. Get messages from Message Queuing:

You can get messages from Windows Message Queuing through the PeekMessage or GetMessage functions. The message queues that Windows saves are grouped by threads (thread), which means that each thread has its own message queue.

2. Send a message

Sending a message to a specified form is typically done through the following two functions: SendMessage and PostMessage. The difference between the two functions is that the PostMessage function simply adds a message to the thread message queue, returns True if added successfully, otherwise returns false, the message is processed, or the result of processing is not known. SendMessage is a bit different, instead of adding the message to the queue, it translates the message directly and invokes the message processing until the message processing is complete before returning. So, if we want to send the message to be executed immediately, we should call SendMessage.

Also, the message sent by SendMessage is not being added to the message queue, so the message sent by SendMessage cannot be obtained through PeekMessage or getmessage.

In addition, some messages with PostMessage will not succeed, such as Wm_settext. So not all the news can be used postmessage.

There are other API functions for sending messages, such as Postthreadmessage,sendmessagecallback,sendmessagetimeout,sendnotifymessage.

Iv. message loops and form procedures

Message loops are the root cause of the persistence of an application. If the loop exits, the application ends.

Let's take a look at what message loops are encapsulated in Delphi:

The first step: The program starts running (run)

Application.initialize; Initialization

Application.createform (TForm1, Form1); Create the main form

Application.Run; Start running, preparing for a message loop

If you do not create the main form, the application can also exist and run.

Step two: Start calling the message loop (handlemessage)

Procedure Tapplication.run;

Begin

Frunning: = True;

Try

Addexitproc (doneapplication);

If Fmainform <> Nil Then

Begin

Case Cmdshow of

SW_SHOWMINNOACTIVE:FMainForm.FWindowState: = wsminimized;

SW_SHOWMAXIMIZED:MainForm.WindowState: = wsmaximized;

End

If Fshowmainform Then

If fmainform.fwindowstate = Wsminimized Then

Minimize Else

Fmainform.visible: = True;

Repeat    // Note: Cycle start

Try

Handlemessage;

Except

HandleException (self);

End

Until Terminated;    // cycle End Condition

End

Finally

Frunning: = False;

End

End

The third step: the processing of messages in the message loop.

Procedure Tapplication.handlemessage;

Var

msg:tmsg;

Begin

If not ProcessMessage (msg) then Idle (msg);

End

function Tapplication.processmessage (var msg:tmsg): Boolean;

Var

Handled:boolean;

Begin

Result: = False;

If PeekMessage (MSG, 0, 0, 0, pm_remove) then

Begin

Result: = True;

If Msg.message <> Wm_quit Then

Begin

Handled: = False;

If Assigned (fonmessage) then Fonmessage (MSG, Handled);

If not ishintmsg (msg) and is Handled and not ismdimsg (msg) and

Not Iskeymsg (msg) and is isdlgmsg (msg) Then

Begin

TranslateMessage (MSG);

DispatchMessage (MSG);

End

End

Else

Fterminate: = True;

End

End

A form procedure is actually a callback function. The so-called callback function is actually a function called by the Windows operating system or by an external program. The callback function generally has the specified parameter format, which is passed to the caller in the address manner. Window procedure is called by the Windows operating system, when a window is created, you need to pass in the callback function address when assigning a handle to the form. Then why do we not see this callback function in our usual programming? This is because our programming tools have generated the default form procedure for us, and the process of doing this is to judge the different message types and then make different processing. For example, you can generate events for keyboard or mouse input, and so on.

V. News and Events

Events are essentially encapsulation of messages and are useful tools that the IDE programming environment provides to simplify programming. This encapsulation is implemented in the form process. Each IDE encapsulates a number of Windows messages, such as:

Event

News

OnActivate

Wm_activate

OnClick

Wm_xbuttondown

OnCreate

Wm_create

OnDblClick

Wm_xbuttondblclick

OnKeyDown

Wm_keydown

OnKeyPress

Wm_char

OnKeyUp

Win_keyup

OnPaint

Wm_paint

OnResize

Wm_size

OnTimer

Wm_timer

With this in mind, we have completed events that can encapsulate ourselves.

Through the above introduction, I believe you have a certain understanding of the Windows message mechanism. Through the Windows message programming, we can not only implement a lot of general functions, but also can realize many IDE class library does not provide the function, in addition, we can also through the message hook, the message interception, change its default processing function, so as to break through the limitations of the platform or software functions, greatly extending the function of the program We can also modify the default form process, respond to messages as required, or customize messages, implement instant communication between programs, and so on. Through more in-depth learning, we will also be exposed to more Windows message mechanism related to other windows relative to the underlying knowledge, if you can, suddenly look back, you will find yourself from the "master" is not far.

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.