Introduction to Windows messages and Windows

Source: Internet
Author: User
Tags drawtext

I. Introduction to Windows ' Messages and Windows:
1, what is windows here I do not introduce, but as a programmer we want to know that Windows is the most important one of our programmers commonly used to be a thing is the message. The window is entered as a message, and the window communicates with the other window with the message.
2, we often say that Windows sent a message to the program, in fact, this refers to a Windows calling program in a function, the function's parameters describe this particular message. This function, which is located in a Windows program, is called a "form message handler." Each form created by the program has a related window message handler. This window message handler is a function that can be used either in a program or in a dynamic-link library. Windows sends a message to a form by invoking a window message handler. The window message handler processes the message and then passes the control back to Windows.
3, in the object-oriented program design, the object is a combination of program and data. A window is an object whose program is a window message handler. The data is the information saved by the window message handlers and the information that Windows saves for each window and that window category in the system.
4. After the Windows program starts executing, Windows establishes a "message queue" for the program. This message queue is used to store messages for various different windows that the program may establish. There is a short program code called "Message loop", which is used to remove messages from the queue and send them to the corresponding window message handlers. Some messages are sent directly to the window message handlers without putting them in the message queue.
Second, a real Windows program:

//Hellowin. C/*------------------------------------------------------------------------Hellowin. C--Displays "Hello, Windows 98!" In client area (c) Charles Petzold, 1998----------------------------------------------- ------------------------*/#include<windows.h>LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);intWINAPI WinMain (hinstance hinstance, hinstance hprevinstance, PSTR szCmdLine,inticmdshow) {    //TEXT Macro--unicode identity    StaticTCHAR szappname[] = TEXT ("Hellowin") ;    HWND hwnd;    MSG msg;         Wndclas Wndclass; //window classWndclass.style= Cs_hredraw | Cs_vredraw;//window class StyleWndclass.lpfnwndproc = WndProc;//window ProcedureWndclass.cbclsextra =0;//Reserve Some extra space in the window structure saved by the class structureWndclass.cbwndextra =0;//Reserve Some extra space in the window structure saved inside WindowsWndclass.hinstance = hinstance;//instance handle of the programWndclass.hicon = LoadIcon (NULL, idi_application);//Load icon ResourceWndclass.hcursor = LoadCursor (NULL, Idc_arrow);//Load Cursor ResourceWndclass.hbrbackground = (hbrush) getstockobject (White_brush);//Getstockobject Get (brushes, brushes, etc.) GDI objectsWndclass.lpszmenuname = NULL;//Specify window class menuWndclass.lpszclassname = Szappname;//Specify window class name    if(! RegisterClass (&wndclass))//Register window class{MessageBox (NULL, TEXT ("This program requires Windows nt!"), Szappname, Mb_iconerror); return 0 ; } hwnd=CreateWindow (Szappname,//window class nameTEXT ("The Hello program"),//Window CaptionWs_overlappedwindow,//window StyleCw_usedefault,//Initial x positionCw_usedefault,//Initial y positionCw_usedefault,//Initial x SizeCw_usedefault,//Initial y sizeNull//parent window handleNull//Menu HandleHINSTANCE,//Program Instance handleNULL); //Creation Parameters//after the window is created, the system allocates a chunk of memory in memory, but the window is not displayed on the display, so two calls are required:ShowWindow (hwnd, icmdshow);//Display windowUpdateWindow (HWND);//will cause the customer area to be drawn//The program takes a message out of the message queue by executing a code called a "message loop"//Note the difference between getmessage (blocking, not returning control if no message is being returned) and PeekMessage (non-blocking, if no message is returned)     while(GetMessage (&msg, NULL,0,0) {translatemessage (&AMP;MSG);//Pass the MSG structure to Windows for some keyboard conversionsDispatchMessage (&AMP;MSG);//Pass the MSG structure to Windows, and Windows sends the message inside to the appropriate window procedure for processing    }    returnMsg.wparam;}//callback type (for system calls)LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {HDC hdc;    Paintstruct PS;    Rect rect; Switch(message) {//when Windows processes the CreateWindow function, the window procedure receives the WM_CREATE message         CaseWm_create:playsound (TEXT ("Hellowin.wav"), NULL, Snd_filename |Snd_async); return 0 ; //When part or all of a window's customer area becomes "invalid", a refresh must be made and WM_PAINT will notify the program         CaseWM_PAINT://The BeginPaint call makes the entire client area valid and returns a "device environment handleHDC = BeginPaint (hwnd, &PS); //When changing the window size, WndProc the client area by calling GetClientRect to get the changed window size .GetClientRect (hwnd, &rect); //outputs formatted text within the specified rangeDrawText (HDC, TEXT ("Hello, Windows 98!"), -1, &rect, Dt_singleline | Dt_center |dt_vcenter); EndPaint (hwnd,&PS); return 0 ; //occurs when the user clicks the Close button         CaseWm_destroy://call PostQuitMessage to respond to WM_DESTROY messages in a standard manner;//postquitmessage (0); //the function inserts a WM_QUIT message in the program's message queue. //GetMessage Returns a non-0 value for all messages that are removed from the message queue except for the Wm_quit message. And when GetMessage takes a wm_quit message, it returns 0.PostQuitMessage (0) ; return 0 ; }    returnDefWindowProc (hwnd, message, WParam, LParam);}

1. Code Analysis:
(1), here you in addition to WinMain you can also see a Wndpro function This function is the legendary message processing function, that is, the message loop is running here is also a program of the heart, with his program can get normal operation, He is transplanted into the window class in the class of the window registration class, and wndclass.lpfnwndproc=wndpro it first.
(2), here I would also like to say that the next CreateWindow and Wndclass is the establishment of the window and Registration window of the relationship between them, like a garage and design car relations, registerclass function registered a Wndclass object, The CreateWindow is then linked to the window class by the lpclassname of the Wndclass object, which is the type of the string.
(3), calls to Windows functions: In this basic framework we call 18 Windows functions as follows:

LoadIcon//load icon generation usingLoadCursor//load the mouse cursor for use by the programGetstockobject//get a graphical objectRegisterClass//registering window categories for program WindowsMessageBox//Show message BoxCreateWindow//Create a window based on the window categoryShowWindow//Display the window on the screenUpdateWindow//indicates that the window is self-updatingGetMessage//getting a message from a message queueTranslateMessage//translating certain keyboard messagesDispatchMessage//to send a message to a window message handlerPlaySound//play a sound fileBeginPaint//Start drawing windowGetClientRect//gets the size of the window display areaDrawText//Display StringEndPaint//End Drawing windowPostQuitMessage//inserting an exit message in a message queueDefWindowProc//perform a default message processing

(4), in this function there are many uppercase and lowercase macro definitions: These explanations
In the above function, there are several uppercase macro definitions:

  prefix: Category use CS window category style Wndclass.style  =cs_hre draw|            cs_vredraw; CW Build window CreateWindow --- (CW) DT Draw Text Drawte     XT ---- (DT) IDI diagram ID LoadIcon (...)    IDC Mouse ID loadcursor (...) MB message box MessageBox ------mb SND Sound Play    Sound (...)        WM window message windowsmessage ------- (WM) WS-window style WindowStyle -----(WS) 

(5), we often ask wparam and lparam What is the difference between what to use: In fact, these two parameters are Win16 and Win32 co-exist when the product is now 32 bits, the original wparam (WORD) is a 16-bit lparam (LONG) is 32-bit,   Now the WParam and lparam are all MS Redefined, and they are usually the constant values associated with a message as follows: WParam is usually a constant value associated with a message, or a handle to a window or control.  LParam is typically a pointer to data in memory. Because wparam, lparam, and pointers are all 32-bit, you can force type conversions when needed. What is specific, related to the message, they are defined in advance.

(6), the Wndpro function returns a value of the form LRESULT, the value is simply defined as a long, where the Wndpro function is designated as a callback form, in fact, is also a WINAPI as a macro definition he is a _ StdCall a right-to-left stack, the legendary callback function (the paper tiger is not afraid).

2, Handle Introduction: The handle is a (usually 32-bit) integer, which represents an object. sufficed in Windows resembles a file handle used in traditional C or MS-DOS programming. The program almost always obtains a handle by calling the window function. The program uses sufficed in the function to represent the object. The handle value is irrelevant to the program, but Windows uses the code name (handle) to use the corresponding object for the code name. What a word handle is, such as you are an object so the handle is your name, if Windows wants you to buy soy sauce Then he will say to you: "XX handle to buy soy sauce", and called the object to buy soy sauce effect is the same, but with the handle will be better management. (I don't know if it would be better to understand that!) ) Three uppercase identifiers for different forms of handles:

Identifier            meaning    hinstance        Execution Entity (program itself) handle        HWND            window handle    HDC                device content handle

Handles are used very frequently such as: Hicon (icon handle), Hcursor (mouse cursor handle), HBRUSH (brush handle), each window in Windows has a sufficed, the program is used to use a window form handle is one of the most important handles that Windows programs handle.

3, I also say the instance bar, in fact, this is the equivalent of you run QQ whole QQ is a instance!

Iii. Registration Window Category: 1, Window according to a window category established, window category to identify Processing window message processing program. The window category defines the window message handlers and other characteristics of the window created by the cited category. When creating a window, define some features that are unique to the window. Before you create a window for your program, you must first call registerclass to register a window category. The function requires only one parameter, a pointer to a structure that points to a wndclass pattern. These structures include two fields that point to a string (LPCTSTR lpszmenuname; LPCTSTR Lpszclassname;--ascii. LPCWSTR Lpszmenuname; LPCWSTR Lpszclassname;--unicode) So the structure defines two different ways in the WINUSER.H table file (Ascii,unicode) in the programming process we don't have to bother! Because it has been processed at predefined time (WNDCLASSA,WNDCLASSW---all with wndclass)! 2, the most important in the form class definition is the Lpfnwndproc and the last field lpszClassName.

3. Window Category He defines the general characteristics of a window, so you can use the same window category to create many different windows, and when you create a window, you may specify more detailed information about the window. The information passed to the RegisterClass function is set in a data structure, and the information passed to the CreateWindow function is set in the individual parameters of the function.

Iv. Message loops:
Windows maintains a "message queue" for each Windows program that is currently executing. After an input event occurs, Windows converts the event into a message and places the message in the program message queue. The program extracts messages from the message queue by executing a piece of program code called the message loop.
Here we look at the next MSG structure:

Typedefstructtagmsg{HWND hwnd; //window handle for receiving messagesUNIT message;//message identifier wm_xxxxWPARAM WPARAM;//32 bits Its meaning and value vary depending on the messageLPARAM LPARAM;                DWORD time; //time the message was placed in the message queuePoint pt;//mouse coordinates when messages are placed in Message Queuing}msg,*PMSG; BOOL GetMessage (lpmsg lpmsg,//address of structure with messageHWND hwnd,//Handle of WindowUINT Wmsgfiltermin,//First messageUINT Wmsgfiltermax//Last message);

This call is paid to Windows with an indicator that points to the MSG structure named this MSG. Lpmsg is a message address, HWND If NULL indicates that the program receives all the messages for all the Windows it establishes itself, Windows populates the individual fields of the message structure with the next message that is taken out of the message queue. A non-0 value is returned as long as the message field is not wm_quit,getmessage out of the message queue.

BOOL translatemessage (    *lpmsg   //  address of structure with message); //  LONG dispatchmessage (    *lpmsg   //  pointer to structure with message);

The MSG structure is also passed back to Windows. Windows then sends the message to the appropriate window message handler for processing. This is where Windows will invoke the message handler, which is the Wndpro function of this window. After the message is processed, WNDPROC returns to Windows, where the window remains in the Despatchmessage call, and after the processing of the DispatchMessage call is finished, Windows returns to the GetMessage call to start the message loop.

Five, the Window message processing program:

1, in the above we introduced a window of the production process and action process: the Registration window category, set up a window, and then display the window on the screen, the program into the message loop, and then constantly remove messages from the Message queue processing.

2, the actual action occurs in the window message processing program. The window message handler determines what is displayed in the display area of the window and how the window product responds to the user input. Window message handlers can be arbitrarily named, and a Windows program may contain multiple window message handlers. A window message handler is always associated with a specific window category that is registered with the registerclass that is called. The CreateWindow function creates a window based on a particular window category. However, depending on a window category, multiple Windows can be created.

Window message handlers are always defined in the following form:

LRESULT CALLBACK WndProc (HWND hwnd,unit message,wparam wparam,lparam LPARAM)

The first four fields of the four parameters and the MSG structure are the same.

3, the program usually does not directly call the window message handler, the message handler is usually called by Windows itself. When a window message handler processes a message, it must pass back all messages that are not processed by the window message handler and should pass to the Windows function named DefWindowProc. WndProc only choose to handle three kinds of messages first: Wm_create,wm_paint,wm_destroy. Wm_create: Handles a window initialization.

4. WM_PAINT: This message notifies the program when some or all of the contents of the window display area are required to be updated to show or become invalid.

What is invalid, invalid means that if the window calls Updatewindows, for example, in the window class we write Style=cs_hredraw|cs_vredraw this means that after the window size changes, the entire window display content becomes invalid.

5. Call Updatewindows to redraw. The processing of WM_PAINT almost always starts with a beginpaint (HWND,&PS) call, ending with EndPaint (HWND,&PS), and PS contains some window message handlers that can be used to update the contents of the display area.

6. In the BeginPaint call, if the foreground of the display area has not been deleted, it is deleted by Windows, which uses the brush specified in the Hbrbackground field in the WNDCLASS structure of the window category to remove the foreground. Beginpain returns a device content handle that can be plotted only in the current region. Endpain releases the device content handle. GetClientRect (Hwnd,&rect) rect is the dimension that returns a window display area.

7. Wm_destroy: This message occurs when a user clicks the Close button or selects close on the program's system menu. The PostQuitMessage (0) is used here to take effect. The function inserts a WM_QUIT message into the program's message queue so that getmessage gets a wm_quit message that returns 0, terminates the program and executes the return msg.wparam;

Vi. queueing messages with non-queued messages: Windows sends a message to a window, which means that Windows invokes a window message handler. However, the Windows program also has a message loop that calls GetMessage to take the message out of the message queue and calls DispatchMessage to send the message to the window message handler.

Messages are divided into "queued" and "non-queued".
1. Queued messages: is placed in the program message queue by Windows. In the message loop of the program, it is re-passed back and assigned to the window message handler. such as keyboard messages, WM_PAINT Windows messages, and so on.
2. Non-queued messages are sent directly to the window message handler when Windows calls the window. Non-queued messages are more likely to appear in a non-queued message when they invoke a queued message signal from a Windows function such as createwindows, keyboard, or mouse input.
3. Queued messages are sent to the message queue, and messages that are not queued are sent to the window message handlers.
Any question, the window message handler will get all the messages from the window-including the queue and non-queued messages. The window message handler is the window's Message center.
4. In many cases, the window message handler must save the information it obtains from the message and use that information when it processes another message. This information can be stored in the window's static or global variables.

Introduction to Windows messages and Windows

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.