In-depth Delphi-Windows messaging mechanism

Source: Internet
Author: User

Http://www.txsz.net/xs/delphi/3/Windows%20%E6%B6%88%E6%81%AF%E6%9C%BA%E5%88%B6.htm

Windows Messaging mechanism

by machine

Is everyone wondering why I haven't talked about Delphi's controls yet?

But don't worry, the content of the in-depth control will soon appear, but before that,

You also need to understand the mechanism of the Windows graphical interface program--windows the message mechanism.

Friends who have used Delphi know that Delphi is a truly object-oriented programming environment,

But not only that, Delphi's object-oriented mechanism is purely based on the windows of the message mechanism on the Delphi Code,

Instead of calling DLLs like VB, VFP, or OCX, by looking at the source code of the Delphi control,

You can see how the whole mechanism is organized, and you can completely control these controls,

Because they're just written in Delphi code, not something that's invisible in a DLL.

So what is the so-called message mechanism of Windows?

Remember when I learned basic, there was no event or anything like that, and the whole process was depicted with a flowchart,

Where the program needs keyboard input, the entire program stops to wait for input and then does something different according to the input.

This would have been fine, but when it came to the graphical interface, the situation was different,

Mouse input is a big problem, and in a multitasking system like windows,

It is impossible for a program to constantly test the state of the device to get input.

In short, the message mechanism under Windows is completely different, and there are many different places, even when compared to simple interrupt events.

In a nutshell, a thread creates a message queue when the form is created, but the form is not necessary to create the message queue in other ways.

Then, the other program, or the Windows system itself, can send a message to this thread to its message queue, notifying the thread that something has happened,

This is the so-called event. Each process can use the GetMessage function to get the first message in its message queue.

GetMessage also automatically removes this message from the message queue and, of course, specifies that the message not be deleted.

I'll talk about this later. The light may still not be imagined, so let's look at the following example:

 ProgramSample3;usesWindows, Messages;varmsg:tmsg;beginPostMessage (0, Wm_user,0,0); //first, force the generation of Message Queuing PeekMessage (MSG,0, Wm_user, Wm_user,0 ); //then here is the so-called message loop, and GetMessage () returns false only if the Wm_quit message is received. whileGetMessage (MSG,0,0,0) Do  begin  End; //here can do the work before the end of the program (after receiving wm_quit)End.

This program will not do anything after it runs, and it will ignore all the messages that Windows sends to it, except Wm_quit,

Because getmessage this function has a feature, when other messages are received, the return value of GetMessage is true,

The return value is False when the wm_quit is received, so the message loop is broken.

When Windows shuts down, Windows automatically sends a WM_QUIT message to the main thread of the program, and the program exits.

The majority of the program's body is like this, there is a message loop, that is, each program is constantly using getmessage to try to get new messages,

Then the processing, the cycle, until the receipt of wm_quit.

And the good thing about it is that when the getmessage is called, if there is no message in the message queue, the function does not return immediately.

Instead, the thread goes to sleep, so that the thread does not waste CPU time because of a continuous loop.

After a new message is received, the thread wakes up, getmessage the received message into a parameter of type tmsg and returns,

So the program can handle the message.

Well, how does this messaging mechanism work with form programs?

In other words, if a program generates a form, how does the program get the user's input message through this message mechanism?

This will start with the process of creating the form. Here's an example of a bit more complicated:

 ProgramSample4;usesWindows, Messages;varmsg:tmsg; Wc:twndclass; //registerclass () the required parameters Hwnd:thandle;//handle to the main formConstClassName='Mainwclass';functionMainwndproc (Handle:thandle; Msgid:uint; WParam, Lparam:integer): LRESULT; stdcall;beginResult:=1;  CaseMsgID ofWm_close:begin//close the message generated by the formifMessageBox (Handle,'Do you want to close this program? ','Example Program-4', mb_iconquestionorMb_yesno)= Idyes ThenDestroyWindow (hWnd)ElseResult:=0;      Exit; End; Wm_destroy:begin//DestroyWindow () generates a message PostQuitMessage (0 ); End; End; //The rest of the message is given to the Windows preset handler function, such as the wm_ncpaint message of the drawing form, such as Result:=DefWindowProc (Handle, MsgID, WParam, LParam);End;begin//First Use RegisterClass () to register the form's class, which is not the class in the Delphi data type Oh! Wc.style:= Cs_hredraworCs_vredraw; Wc.lpfnwndproc:= @MainWndProc; //address of the message handler function Wc.hinstance:= HInstance; //the handle of the program is also the base address Wc.hicon:= LoadIcon (0, PChar (idi_application)); Wc.hcursor:= LoadCursor (0, Idc_arrow); //icon Wc.hbrbackground:= Getstockobject (White_brush); //Background Painting brush Wc.lpszclassname:= ClassName; //the constants defined earlierifRegisterClass (WC) =0  ThenHalt (0 ); HWnd:= CreateWindowEx (0, ClassName,//The name of the class that was just registered'Sample', //the title of the form Ws_overlappedwindow,//The form has the title bar, the system menu, the most-sized menu, and the extruded border Integer (cw_usedefault), Integer (Cw_usedefault), Integer (cw_usedefault), integer (Cw_usedefault),0,0, HINSTANCE,Nil ); ifHWnd =0  ThenHalt (0 );  ShowWindow (HWnd, cmdshow);  UpdateWindow (HWND);  whileGetMessage (MSG,0,0,0) Do  beginTranslateMessage (MSG); DispatchMessage (MSG); //the API dispatches messages to the appropriate form message handler functionEnd; ExitCode:=Msg.wparam;End.

Because there are more things to say, the API description, definitions, please see the SDK yourself.

Before you create a form, you first need to register the form's class with Windows.

The so-called register form class is to populate the data for a TWNDCLASS structure, set the properties of the class, and pass it to Registerwindowclass ().

Among these attributes is a pointer to the form message handler function for this class, followed by the name of the class.

When you create a main form with CreateWindowEx, you can create a form of this class based on the name of the class.

So what does a form message handler do for a function?

It is important to note that a thread can create multiple forms, which can be created by your program, or Windows may be created during the course of your program's operation.

For example, when a user taps the system icon in the upper-left corner of the form, Windows generates a system menu-

In Windows, all the things you can see, including edit boxes, buttons, are called forms, not the main form of the program, the subform is called the form!

Then the problem comes along, with only one message queue in one thread, but with so many forms,

If all the messages are processed in the message loop of the main program, it is very difficult to write large programs, and the messy programs are cumbersome to maintain.

So this form message handler function (Window Procedure) works because you can write a message handler function for each class.

So it's only necessary to pass the message to the corresponding class's message handler when you receive the message from the corresponding form.

The entire program becomes very structured.

The program does not even need to record the corresponding class message handler function for each form,

Directly calling DispatchMessage () Windows will automatically use the appropriate message handler function.

Another function Defwindowpro () is also a key point, try to omit this line, to see what effect after the program run?

In fact, after doing so, you won't even see the form, Windows just retains a position on the screen for the form you created.

Why is it? Your program did not draw the form Ah!

Don't think that Windows will do everything for you after you create the form, in fact DefWindowProc () processed the WM_PAINT and Wm_ncpaint messages and finished the work of the drawing form.

DefWindowProc for the General Program main form do a lot of such behind-the-scenes work Oh!

This shows that the message is not just the user's mouse, keyboard input message, but the program and Windows System Contact tool,

Later, you will know that there is a lot of use for the message, and the writing of the Delphi control is often inseparable from the message.

In-depth Delphi-Windows messaging mechanism

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.