How Windows programs work

Source: Internet
Author: User
Tags button type textout

How Windows programs work

1. The relationship between the application, the operating system, and the hardware

This involves message and Message Queuing, in which the operating system passes the perceived event to the application through a message mechanism.
The operating system wraps each event into a struct-body msg called a message to be passed to the application.
The process by which the operating system responds to events is called a message response.

typedefstruct tagMSG {     // msg      HWND hwnd;    UINT message;    WPARAM wParam;    LPARAM lParam;    DWORD time;    POINT pt; } MSG;

2.Windows API
The Windows operating system provides an interface to application programming (application Programming Interface), called the Windows API

3. Window Handle
Frankly speaking, the window handle is an identity of the resource, can also be regarded as a pointer, the operating system to manage and manipulate these resources, all through the handle to find the corresponding resources. By type of resource, the handle can be subdivided into the handle of various types, such as the icon handle (HICON), the cursor handle (hcursor), the window handle (HWND), the application instance handle (HINSTANCE), and so on.
The operating system gives each window a unique identification number that is the window handle, and the window handle in the program HWND is often used

4.WinMain function
The operating system calls the WinMain function to start our application, so it is necessary to understand this function.
We look at the definition of this function in MSDN:

int WINAPI WinMain(         //windows入口函数  HINSTANCE hInstance,      // handle to current instance  HINSTANCE hPrevInstance,  // handle to previous instance  LPSTR lpCmdLine,          // command line  int nCmdShow              // show state)

the creation process of the 5.Windows window
Specific can be divided into the following several steps:
1. Design Window class

    //Design window classWndclass wndcls;//struct-body Variables for window classesWndcls.cbclsextra =0;//class load additional space, typically 0Wndcls.cbwndextra =0;//window with additional space allocated, typically 0Wndcls.hbrbackground = (hbrush) getstockobject (Black_brush);//Paint brush HandleWndcls.hcursor = LoadCursor (NULL, Idc_cross);The //cursor handle, NULL indicates the use of a standard set, and subsequent parameters represent a specific type ofWndcls.hicon = LoadIcon (NULL, Idi_error);//icon handle, NULL indicates the use of the default set, and subsequent parameters represent a specificWndcls.hinstance = hinstance;//Window handleWndcls.lpfnwndproc = Winsunproc;//callback functionWndcls.lpszclassname ="HelloWorld";//Window nameWndcls.lpszmenuname =NULL;//The name of the menuWndcls.style = Cs_hredraw | Cs_vredraw;//window style, use phase or the way to add function

2. Registration window class

RegisterClass(&wndcls);//注册窗口

3. Creating a Window class

//window must be defined before creating a window handle-identity windowHWND hwnd;//Create windowhwnd = CreateWindow ("HelloWorld",//The name of the class, same as the WNDCLASS name created previously        "Myfirstmfcapp",//Window nameWs_overlappedwindow & ~ Ws_maximizebox/ * Remove the Maximize button * /,//window Default properties, Cascade menu, System menu, Minimum maximize button, using BITS phase or technology        0,The x-coordinate of the upper-left corner of the window (specifies the default value of Cw_usedefault, the value of the set y-coordinate is ignored)        0,//Window upper left corner y-coordinate         -,//Window width (Specifies the default value of Cw_usedefault, the value of set height is ignored)         -,//Window height        NULL,//Parent window handle, no parent window set to null        NULL,//Menu handle, no menu set to nullHINSTANCE,//Handle to the current program instance        NULL);//This parameter is not required for the time being

4. display window class

ShowWindow(hwnd,SW_SHOWNORMAL);//窗口句柄,显示状态(最大化,最小化,正常显示)

5. Updating the window class

UpdateWindow(hwnd);//更新窗口

6. Turn on the message loop

 msg msg;    //the operating system assigns a message queue to each program  /* when the GetMessage function gets the wm_quit message from the thread's message queue, returns 0, and the program exits immediately when the GetMessage function is not wm_quit from the thread's message queue, Return non 0, continue to loop receive message */ //remove message from message queue: Message variable, all messages, start of message (0 receive all messages), end of message (0 receive all messages)  while (getmessage (&msg,null, 0 , 0 ) )  {translatemessage (& msg) ;        //convert the corresponding message (WM_CHAR message)  dispatchmessage (&msg) ; //dispatch messages to the operating system, the operating system calls the user to write the window when the custom window callback function-winsunproc }  

callback function for 7.Windows window
The following is a schematic diagram of a Windows message loop that can help us better understand the process of message processing:

As you can see, the last called window callback function is our own definition, which gives us the way we want to handle the message.
Here is the definition of the window callback function (procedure function)

LRESULT CALLBACK Winsunproc (//Window procedure function--also called window callback functionHWND hwnd,//Handle to window handleUINT umsg,//Message identifier messages handleWPARAM WPARAM,//First message parameter additional parametersLPARAM LPARAM//Second Message parameter second message additional parameters){Switch(umsg)//Judgment message type{//Keyboard Press the message     CaseWM_CHAR:Charszchar[ -];sprintf(Szchar,"Char is%d", WParam);//Window handle, Message Text, dialog box caption, dialog box type (0 for MB_OK only one OK button, Mb_yesno with OK and Cancel button)MessageBox (Hwnd,szchar,"Hello",0); Break;//left mouse button to press the message     CaseWm_lbuttondown:messagebox (hwnd,"Mouse clicked","Hello",0); HDC hdc;//Automatically determine platform drive device typeHDC = GetDC (hwnd);The //parameter is the window handle (equivalent to putting the window on the canvas), gets the DC handle, is responsible for displaying        //Output text function: DC handle, start of text x, y coordinates, text, string lengthTextOut (HDC,0, -,"Hello",strlen("Hello"));//Release DC,DC is a data structure maintained internally by the system and will cause a memory leak if not releasedReleaseDC (HWND,HDC); Break;//Screen Redraw message     CaseWM_PAINT:HDC HDC; Paintstruct PS;//painting for the specified windowHdc=beginpaint (HWND,&PS);//** can only be used in WM_PAINT * *        //Keep text on the windowTextOut (HDC,0,0,"Hello",strlen("Hello"));//Finish painting, release DCEndPaint (HWND,&PS);//** can only be used in WM_PAINT * *         Break;//window close Message     CaseWm_close://messagebox execution successfully returns the clicked button type information        //Be sure to perform the judgment here        if(Idyes==messagebox (hwnd,"Is it really over?" ","Hello", Mb_yesno)) {//Destroy window to send Wm_destroy message            //After the function is executed, the window will be destroyed.DestroyWindow (HWND); } Break; CaseWm_destroy://0 on behalf of exit code        /* The function: Post a wm_quit message into the thread's message queue and then immediately return when the GetMessage function returns a wm_quit message from the thread's message queue, returning 0, the program exits immediately when the GetMessage function The message queue from the thread is not wm_quit, return non 0, continue to loop receive message * /PostQuitMessage (0);/* in DestroyWindow (HWND), determine whether the end does not perform judgment here, because DestroyWindow (HWND); After the function is executed, the window has been destroyed and it is meaningless to judge. if (Idyes==messagebox (HWND), is it really over?        "," Hello ", Mb_yesno)) {postquitmessage (0); }*/         Break;default://For messages that are not interested, let the system do the default processing of messages, essential processing        returnDefWindowProc (Hwnd,umsg,wparam,lparam); }return 0;}

The window callback function is specified:

wndcls.lpfnWndProc = WinSunProc;//指定这个窗口类的回调函数为WinSunProc

6.Windows function calling convention
function calling conventions: rules that specify the order in which function parameters are passed and the purge of stacks

function calling convention in VC:
__cdecl Convention : The standard C language calling convention, VC + + compilation options default Use this way

__stdcall Conventions :
Standard calling convention, also known as Pascal calling convention, Delphi uses this Convention
In addition to the variable parameter APIs, the __stdcall conventions are used.
Using this calling convention in VCs, you must add the CALLBACK macro definition #define CALLBACK __stdcall
The callback function must use the __stdcall method, which is more intuitive to indicate that the function is a callback function

7.Windows Naming Conventions

8. Bit characteristics of variables
A class of variables is often used in our programs, and each bit of this variable corresponds to a particular feature. When a bit of the variable is 1 o'clock, it indicates that the attribute corresponds to that bit, and when that bit is 0 o'clock, there is no attribute corresponding to that bit. Multiple bits of this variable are 1 o'clock, which is a combination of multiple attributes.
For example:

Specifies the style of the window for a combination of three types

style = CS_VREDRAW | CS_HREDRAW | CS_NOCLOSE;

If one of the features is removed, the inverse (~) and then the (&) operation will enable

style & ~CS_NOCLOSE;//去掉最后一个特性

9.Visual C + + program compilation process Diagram

As long as we compile the program, then this process should not be unfamiliar, the resulting intermediate file *.obj, the resulting target file is the. exe file.

Summary
When we are writing Windows programs, be sure to learn to find MSDN documentation, MSDN is the best learning material.

How Windows programs work

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.