Win32 program Window program, and message mechanism

Source: Internet
Author: User
Tags message queue sprintf
Win32 Program Value window program, and message mechanism I. INTRODUCTION

Through the previous talk. We understand that the window is actually drawn. And it's the process of drawing. So the essence of the window is to draw. But we now see the window program. You can click the Close button. Using a mouse click will react.

And how we're going to achieve that.

In fact, the mouse click is generated a message. Window encapsulates the message as a message structure.  Sent to our window program. So how does Windows know which window you clicked on?

That is true. When we click. The click coordinates are recorded. messages. Wait. Windows system will accept. Then traverse the winobj structure in the kernel. And this structure stores the Window object. The Window object corresponds to the message thread.

So a layer of Windows traversal. The corresponding window and the corresponding thread of the window are found. Then send it to our app.

That's what we need to know. To know how the message was produced. How it is delivered. Then the following programming is understood.

For example:

Each application has a thread object. And this thread object if the window is created. The Window object is in the kernel.

If we have a mouse click on the message. Keyboard messages and so on. The operating system iterates through the Window object. The Window object also holds the thread object that corresponds to creating the Window object. There is a message queue in this thread object.

In this case the operating system encapsulates the message sent to our Window object.

Second, wind window class structure. Create a window program. 1. Problems needing attention in window programming

Window programming in Windows. The entry point has been changed to WinMain. There are four parameters.

As shown in the following code

int apientry wWinMain (_in_ hinstance hinstance,               //window instance handle hinstance stands for module meaning HWND stands for window meaning. Handle represents a Kernel object. HDC device context.                     _in_opt_ hinstance hPrevInstance,        //parent window handle. No need.                     _in_ lpwstr    lpCmdLine,                //Command line arguments                      int       ncmdshow)                 //command. Maximize commands. or minimize the command. {       return 0 ;}
wWinMain  because Unicode differs from ASCII. So I'm Unicode using wWinMain. Version A is used WinMain
2. Debugging the Windows programming method

In Windows, our debugger is not easy to debug with printf. or print out. We can operate with two APIs.

1.Sprintf () format string.

2.OutPutDebugString () output debug string.

Specific two APIs. No longer burdensome. Baidu search can be.

Because OutputDebugString () can only print a fixed string. Use sprintf to format the string. As shown in the following code.

int apientry wWinMain (_in_ hinstance hinstance,                     _in_opt_ hinstance hprevinstance,                     _in_ lpwstr    lpCmdLine,                      int        ncmdshow) {      TCHAR str[] = {NULL};      " %s "), TEXT ("HelloWin32"));      Use the W version because it is Unicode.    OutputDebugStringW (str);     return 0 ;}

After we have compiled the program. You can use the DebugView tool to view it.

3. Procedure for Window programming

1. Create a window class. window styles provided by Windows. We need to be given.

2. Register window class. Create a window we need to register with the Windows system.

3. Create a window. If the registration window succeeds. Then we need to create this window. and display and update.

4. Message Processing

4. Main structure required for window programming

Windows has been created for us. This structure is the WNDCLASSEXW structure.

Look at what's in this structure.

struct _wndclassex {     UINT       cbsize;                   The size of the extension. Oneself wndclass size itself.    UINT       style;                    Style    WNDPROC    lpfnwndproc;              Window callback. The message is going to enter    this callback int        cbclsextra;                   int         Cbwndextra;      HInstance  hinstance;                Instance handle    hicon      hicon;                    Icon    hcursor    hcursor;                  Cursor    hbrush     hbrbackground;            Background    lpctstr    lpszmenuname;             Menu name    lpctstr    lpszclassname;            Class name    hicon      hiconsm;                  

This structure means. What style is your window? size. Whether there is an icon. Where is the message handler and so on. We need to give the designation.

5. Complete code.
//WindoS.cpp: Defines the entry point for the application. //#include"stdafx.h"#include<stdio.h>#include<stdlib.h>#include"WindoS.h"#defineMax_loadstring 100//Global Variables:HINSTANCE HInst;//Current InstanceWCHAR sztitle[max_loadstring] = TEXT ("the first one of my window");//title bar TextWCHAR szwindowclass[max_loadstring] = TEXT ("Mywindow");//main window class name//The forward declaration of the function contained in this code module:LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);intapientry wWinMain (_in_ hinstance hinstance, _in_opt_ hinstance hprevinstance, _in_ lpwstr lpCmdLine, _in_intncmdshow) {    //1. custom Window StylesWndclass Wcex; Wcex.style= Cs_hredraw |Cs_vredraw; Wcex.lpfnwndproc= WndProc;//Set CallbackWcex.cbclsextra =0; Wcex.cbwndextra=0; Wcex.hinstance=hinstance; Set the module instance handle Wcex.hicon=LoadIcon (hinstance, Makeintresource (Idi_windos)); Wcex.hcursor=loadcursor (nullptr, Idc_arrow); Wcex.hbrbackground= (Hbrush) (Color_window +1); Set the background color Wcex.lpszmenuname=Makeintresourcew (Idc_windos); Wcex.lpszclassname=Szwindowclass; Set class name
The above is mainly 4 parameters useful. callback function background color module handle. Class name//2. Registration window classBOOL BRet = registerclass (&wcex);//A registerclass U registerclassw extension REGISTERCLASSEXA/EXW if(BRet = =FALSE) { return 0; } //3. Create window and Show Update windowHWND hwnd =Createwindoww (Szwindowclass,//Our class name SzTitle,//Our custom window name Ws_overlappedwindow,//Window creation style Cw_usedefault,0, Cw_usedefault,0, nullptr, nullptr, HINSTANCE,//instance handle nullptr); The above important is 4 parameters. The remaining parameters are queried under MSDN. if(!hWnd) { returnFALSE; } ShowWindow (HWnd, sw_show); UpdateWindow (HWND); //4. Message loops.msg msg; /*The 1 parameter is the message structure. The operating system fills in the message. 2 parameter window handles because each thread can have more than one window. The message that I'm going to take that window. The 3.4 parameter indicates the message that I want to fetch this window. The next three parameters belong to the filter condition /c3>*/ while((BRet = GetMessage (&msg, NULL,0,0)) !=0) { if(BRet = =-1) { //handle the error and possibly exit } Else{TranslateMessage (&AMP;MSG);//the keyboard message is converted to lowercase.DispatchMessage (&AMP;MSG);//distribute the message. Pass our message to our callback function processing. Important functions. This message will send the Windows message to the callback function that we gave when we defined the window class. So that we can execute our code based on the message . } } return 0;}////functions: WndProc (HWND, UINT, WPARAM, LPARAM)////Purpose: Processes the message of the main window. ////wm_command-Processing Application Menu//WM_PAINT-Draw the main window//Wm_destroy-Sends an exit message and returns////Our window callback.LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {Switch(message) { Casewm_command://Menu message type {intWmid =LoWord (WParam); The lower two-bit is the menu ID. You can manipulate our window according to the menu ID//Analysis Menu Selection: Switch(wmid) { CaseIdm_exit:destroywindow (HWND); Break; default: returnDefWindowProc (hWnd, message, WParam, LParam); If it is not processed, you must call this function to teach the default window callback processing}} Break; Casewm_paint: {paintstruct ps; HDC HDC= BeginPaint (HWnd, &PS); //TODO: Add any drawing code here that uses HDC ...LineTo (HDC,0, -); EndPaint (HWnd,&PS); } Break; CaseWm_destroy:postquitmessage (0); Break; default: returnDefWindowProc (hWnd, message, WParam, LParam); } return 0;}

The result of the creation completed

III. message Types

We have our message type in our callback. We can judge the message type for our different operations.

such as menu messages.

Wm_command. If this is the message, then the additional information such as the wparam of the callback function is the additional message of the WM_COMMAND. We can take the low to get the menu ID of the operation. Then the message is processed.

WM_PAINT This message is a drawn message. We know. The window is constantly drawn. So the drawing of the message will always come.

The Wm_destroy window closes the message. If this message is accepted, the call API passes the exit message to Message Queuing (MSG). The outer main thread ends at this point.

Specific API:

PostQuitMessage (0);

The current specific message also needs to be queried for MSDN. Because there are many kinds of messages.

Windows messages are all beginning with the WM.

such as querying WM_COMMAND messages

Can see clearly. She'll tell you if it's WM_COMMAND news. Then the parameters of the callback function. What is meant by the distinction.

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.