Windows programming the second time windows program's life and death (on)

Source: Internet
Author: User

----- A friend passing by, if you find an error or have good suggestions, please leave a message below. Thank you! -----

Introduction

"Windows programs are divided into two parts: 'program Code' and 'User interface resource'. The two parts are finally integrated into a complete EXE file using the RC Compiler (resource compiler. The so-called UI resources refer to functional menus, dialog box appearances, program icons, and cursor shapes. The internal content of these UI resources (two-step code libraries are used to assist various tools and are available with various extension names, such as .icow.bmp and. cur. Programmers must describe them in a so-called resource description file (. Rc. After reading the description of the RC file, the RC compiler will generate a. Res file for all UI resource files and combine it with the program code. This is a complete Windows Executable ."

The above is a piece of discussion about the windows program development process in "getting down to MFC" by Mr. Hou Jie. I think he is very incisive and concise about the two aspects of Windows programs, this topic is here to share with you. I will also reference the content in his book below.

My advice

Speaking of Windows programming, I think we should first understand the entire mechanism and process of Windows programs from birth to death. When you understand Microsoft's "Game rule", I think the subsequent study will be very easy for you. Therefore, please read the content carefully.

There are still a lot of things I want to explain in these two cases. I want to explain the windows program mechanism and introduce many concepts in windows. Here, I really appreciate Mr. Wang Shuang's teaching point-knowledge shielding. When the concepts are used, I will explain them again. If you don't need them, I will not mention them first. Many books start by throwing out a lot of concepts first, which will make readers confused, instead, it increases the reader's fear. I think that introducing concepts while using them will give readers a better understanding. (At least for me ).

I would also like to emphasize that the main content of these two replies is to explain the running mechanism. I plan to read the program while talking about the mechanism. Considering that many concepts and many functions are the first contact, I am only engaged in the form of "freehand. As long as you have a good understanding of this mechanism and process, you are successful. I will give a brief introduction to the concept (the small text content is an extension of the concept, readers can look at it). I don't understand it. This is normal. Please continue, from the usage of the concept below, you will gradually understand the meaning of this concept. The process of understanding this concept is just as we learned when we were young, after hearing more, you can understand it (now you don't have to worry about it ). I will only talk about the functions of many functions. Please do not worry about the specific usage and why. (I will explain the function usage later. You will read more about it later, can be written out with closed eyes, so you don't have to worry about it for a while.) In case of distraction, this damages the consistency of the process of learning about the windows mechanism and program, keep in mind our purpose-to have a macro and overall understanding of Windows mechanisms and programs, while others are floating clouds, haha.

First come to the previous Code-please do not be afraid

 

1. # include <windows. h> 2. lresult callback winsunproc (3. hwnd, // handle to window4.uint umsg, // message identifier5.wparam wparam, // first message parameter6.lparam lparam // second message parameter7.); 8.int winapi winmain (9. hinstance, // handle to current instance10.hinstance hprevinstance, // handle to previous instance11.lpstr lpcmdline, // command line12.int ncmdshow // show sta Te13.) 14. {15. wndclass wndcls; // defines a wndcls window class Object 16. wndcls. cbclsextra = 0; // storage space occupied by class variables 17. wndcls. cbwndextra = 0; // storage space occupied by instance variables 18. wndcls. hbrbackground = (hbrush) getstockobject (black_brush); // specify the window class paint brush handle 19. wndcls. hcursor = loadcursor (null, idc_arrow); // specify the window class cursor handle 20. wndcls. hicon = loadicon (null, idi_application); // specify the handle of the window class icon 21. wndcls. hinstance = hinstance; // instance handle of the program that contains the Window Process 22. wndcls. lpfnwndproc = winsunproc; // point to window procedure function 23. Wndcls. lpszclassname = "Hello World"; // specify the window class name 24. wndcls. lpszmenuname = NULL; // specify the menu resource name 25. wndcls. style = cs_hredraw | cs_vredraw; // specify the window style 26. registerclass (& wndcls); // registration window 27. hwnd; // defines the handle variable 28. hwnd = createwindow // create a window. The system returns the handle allocated to the window 29. ("Hello World", // class name, which specifies the class 30 to which the window belongs. "Hello World Program", // window name, that is, the text 31 displayed in the title bar. ws_overlappedwindow, // the style of the window is 32.0, // The initial X coordinate 33.0 in the upper left corner of the window relative to the upper left corner of the screen, // The initial y coordinate 34.60 in the upper left corner of the window relative to the upper left corner of the screen 0, // The window width is 35.400, // The window height is 36. null, // the handle of the parent window of a child window, or the handle of the owner window of the window 37. null, // menu handle 38. hinstance, // instance handle of the application that creates the window object 39. null); // additional parameter 40 specified during window creation. showwindow (hwnd, sw_shownormal); display window 41. updatewindow (hwnd); Update window 42.msg MSG; 43. while (getmessage (& MSG, null, 0, 0) 44. {45. translatemessage (& MSG); 46. dispatchmessage (& MSG); 47 .} 48. return MSG. wparam; 49 .} 50. lresult callback winsunproc (51. hwnd, // handle to window52.uint Umsg, // message identifier53.wparam wparam, // first message parameter54.lparam lparam // second message parameter55.) 56. {57. switch (umsg) 58. {59. case wm_create: 60. messageBox (hwnd, "window created", "message", mb_ OK); 61. break; 62. case wm_paint: 63.hdc HDC; 64. paintstruct pS; 65.hdc= beginpaint (hwnd, & PS); 66. textout (HDC, 0, 0, "Hello world! ", Strlen (" Hello world! "); 67. endpaint (hwnd, & PS); 68. break; 69. case wm_destroy: 70. postquitmessage (0); 71. break; 72. default: 73. return defwindowproc (hwnd, umsg, wparam, lparam); 74 .} 75. return 0; 76 .}

  

Open vc6.0 in Windows XP (although it is a bit old, but it is enough for us), select new from the File menu, and click the project tag in the NEM dialog box, select Win32 application. Enter the project name and location, and click OK. Select empty workspace in the next dialog box, and then press finish. After entering the project, create a new C ++ sourse file, paste the above Code, click the buildexecute button, a prompt box () appears, click OK, A window () appears ().

 

 

Concepts:

WindowIt is a rectangular area related to an application on the screen. It is a visual interface between the user and the application that generates the window. It receives user input, the output content is displayed in text or graphic format. For an application, a window is a rectangular area on the screen controlled by the application. The application creates and controls all aspects of the window. When you start an application, a window is created. The program responds to objects in the user operation window.

It generally consists of a border, a title bar, a minimal icon in the control bar, a maximum icon, a horizontal scroll bar that closes the icon, a vertical scroll bar, a menu bar, and a customer area. ①

For example, a common notepad is a good example:

 

WindowsProgram Running Mechanism-message-based, event-driven(Reference Hou Jie's "Let's get started with MFC")

Concepts:

Events and messages

An event is triggered by a user (the person who operates the computer) and can only be triggered by the user (if the user presses the mouse button, a mouse event is generated). The operating system can feel the event triggered by the user, this event is converted into a (specific) message and sent to the Message Queue of the program. ②

 

Message Queue

The message is sent to the queue. "Message Queue" is the container that stores messages during message transmission. The message queue manager acts as a man-in-the-middle when a message is relayed from its source to its target. The main purpose of a queue is to provide a route and ensure message transmission. If the receiver is unavailable when a message is sent, the Message Queue retains the message until it can be passed successfully. (From Baidu encyclopedia)

 

Windows programs are driven by external events. In other words, the program keeps waiting (using a while loop), waiting for any possible input, making judgments, and then doing the appropriate processing. After the above "input" is captured by the operating system, it enters the program in the form of a message (a data structure. How does the operating system capture events that occur on peripheral devices (such as the keyboard and mouse? Oh, the user module ③ (do not care about it first) is in charge of various peripheral drivers, and each of them has a detection loop.

If you classify various "inputs" obtained by the application, messages generated by hardware devices (such as mouse movement or press on the keyboard) can be classified and placed in the system Message Queue (system Message Queue) and messages sent by windows or other Windows programs are stored in application message queue. From the application's perspective, a message is a message. There is no big difference in where it comes from or where it is stored.GetmessageThe API gets a message, and the life of the program is driven by it. All gui (graphical user interface, graphical user interface) systems, including unix x Windows and OS/2 Presentation manager, are message-based event-driven systems.

As you can imagine, every Windows program should have a loop as follows (just familiarize yourself with it ):

MSG;

While (getmessage (& MSG, null )){

Translatemessage (& MSG );

Dispatchmessage (& MSG );

}

// All the above functions are Windows API functions

Only understand that this while loop can continuously process messages.

 

WindowsProgram life and death-start to analyze the code!

Don't be frightened by the number of lines in the above code. That's why so many lines generate a window. There is no way that Microsoft is doing this. This simple window can be said to be a small, dirty one. But almost all Windows programs have extensions for the skeleton. If you understand it, you will have half of the Basic Windows programming. The rest of the work is to learn functions and fill it in.

The life of a program involves three stages: birth, operation, and death ......

Birth:

Just as the entry point in the C program is the function main, the entry point of the Windows program is winmain, which always appears like this: see row 8 (I will emphasize the function only, meanings of specific usage parameters will be discussed later)

Cite sun Xin's wonderful explanation:

"To create a complete window, follow these steps:

Design a window class;

Registration window class;

Create window;

Display and update window.

(Remember this order first. Do not ask why)

1Design a window class

A complete window has many features, including the cursor (shape when the mouse enters the window), icon, background color, and so on. The window creation process is similar to the automobile manufacturing process. Before producing a model car, we must first design the model car, draw the structure diagram of the car on the drawing, and design each part, at the same time, a loud name should also be given to the model, such as "Audi A6 ". After completing the design, you can use the "Audi A6" model to produce cars.

Similarly, before creating a window, you must design the window type to specify the features of the window. When

However, when we design a window, it is not as complicated as car design,BecauseWindowsAlready defined for us

The basic attributes of a window, we just need to fill in the parts that need to be filled in like the blank questions during the exam, a window is designed.(Wonderful metaphor )"

 

Line 15-line 25: defines a wndcls window class object and fills it in. See Code comments (skip this step if you encounter a new concept or do not understand it)

 

"2. Registration window class

After designing a vehicle, the vehicle must be approved by the relevant state departments before it can be produced. Same

After designing the window class (wndclass), you need to call the registerclass function to register it. Note:

You can create a window of this type only after the workbook is created ."

 

Row 26: Registration window

 

"3. Create window -- step3

After the window class is designed and successfully registered, you can use the createwindow function to generate

Window ."

 

Line 27-line 39: create a window (skip this step if you encounter a new concept or do not understand it)

 

"4. Display and update window

(1) display window

After the window is created, we need to display it, which is the same as pushing it to the market after automobile production. Call

Function showwindow to display the window.

(2) Update window

After calling the showwindow function, we call updatewindow to refresh the window, just like

We bought a new house and needed to be renovated ."

 

Rows 41 and 41: Display and update window

 

Run:

Please review the previous "windows program running mechanism-message-based, event-driven". After a program is created from a series of complex processes and displayed on the screen, the program is always waiting for messages, then process the message, which means it is "alive ".

How does a program wait for a message and process it? Please refer to the code. We are now in the while message loop.

See row 43-49. (You only need to know the function. Now you don't have to go into the principle and usage)

The getmessage function can retrieve messages related to the connection to the application window from the Message Queue (in general, the function returns a non-zero value for the loop to continue, when the function returns zero, and the message loop ends, we will talk about it later), and store the specific content of the message in a variable with the MSG type (I .e., MSG, MSG ), then, the function translatemessage translates the message (translated later). Then, the function dispatchmessage sends the message to an appropriate "object" for processing.

When the while message loop is so reciprocating, the program will be able to "live" and continue to wait for messages and process messages.

 

This mysterious "object" is calledWindow Process,It is a function (that is, row 50-76, Row 2-7 is the declaration of this function), used to process messages. If you observe carefully, you will find that the main body of this function is the switch selection statement. What is the selected wm_create, wm_paint, and wm_destroy? You may have guessed it, these are the messages to be specially processed. If the incoming messages do not respond to their case segments, they will all be handled by default segments (it seems necessary ). It seems that the secrets of windows have gradually been lifted by us! A Windows program is created and displayed on the desktop first, this requires designing a window class, registering a window class, creating a window, displaying and updating a window. What functions do you want, in the window process, the switch function selects a specific case segment in the statement to process messages related to your function. For irrelevant messages, the first rate is handled by the default segment. It can be said that the difference between many applications lies in the differences in their window processes. As for the while message loop, This is a fixed writing method. As long as we write this, the specific message routing is automatically completed by the Windows system, so we don't have to worry about it.

Death:

At this point, the reader may be able to infer some information about the program's death: The Window program's "death" must be a message received and responded by the window function, so that the window is destroyed, at the same time, the while message loop is also ended. (Now let's get to know about it, and go deeper next time)

 

This is the first time I have mentioned this. I hope that the readers will have a certain impression on the "life" of Windows programs and its operating mechanism, so they can look at it from a macro perspective, then I can feel satisfied. In this case, we mainly understand the usage and related details of functions in the code. Now, you will have a future.

 

① You may not be familiar with it:

Control BoxIs a small image in the upper left corner of each window, which is used by every application. Click the mouse button on the control icon to display the system menu in windows. The System Menu provides standard operations such as restoration, movement, size, minimization, maximization, and shutdown.

UsuallyCustomer ZoneOccupies the largest part of the window (that is, the area in the notepad that can be written ). This is the basic Output Area of the application. Applications should be used to manage customer zones in a complex manner. In addition, applications can be output to the customer zone.

 

② Supplement:

We usually say "Something happened" and "send a message ". For example, when a mouse is clicked on the desktop, windows first knows how this happened, and then uses the sendmessage function to send a message to the desktop, proving that something happened. This is the principle of "event-driven, message processing.

An event is a user-triggered action.
A message is a message transmitted to the system. It is emphasized that:
It can be said that "the user triggers an event", rather than "the user triggers a message ".
Users can only trigger events, but events can only be triggered by users.
After an event is generated, it is converted into a message by the operating system. Therefore, a message may be generated by an event or by the operating system ).
One message may generate another message, but one message cannot generate one event-the time can only be triggered by the user.

Summary (Event: message source)
Event: it can only be generated by users through peripheral input.
Message: (three sources are used to generate the message)
(1) generated by the operating system.
(2) events triggered by users are converted.
(3) It is generated by another message.

 

The above is quoted from the difference between events and messages

 

Windows messages can be divided into four types:
(1)Input message: Responds to keyboard and mouse input. Such input messages are first placed in the system message queue, and then Windows sends them to the application message queue for processing.
(2)Control Messages: It is used to communicate with special control objects in windows, such as dialog boxes, list boxes, and buttons. Such messages are generally sent directly to the control object instead of through the application's message queue.
(3)System message: Responds to stylized events or system clock interruptions. Some system messages, such as most DDE messages (messages used for Dynamic Data Exchange between programs), must be sent through the windows system message queue. Some system messages, such as window creation and deletion, are directly sent to the application's message queue.
(4)User message: These messages are created by the programmer. Generally, these messages are processed only from one part of the application to another part of the application and will not be left. User messages are often used to process menu operations: a user message corresponds to an option in the menu and is processed when it appears in the application queue.

Module
In Windows, the term "module" is generally a set of executable code and data that can be loaded into the memory. More specifically, a module refers to one. EXE file (also called application module), DLL-Dynamic Linking Library, also known as dynamic link library module or DLL module), or a device driver, it may also be a program containing data resources that can be accessed by another program. The term module is also used to specify a self-contained program. For example, a source file that can be compiled separately or the target program generated after the source file is processed by the compiler. When creating a program, the term module is used to indicate a module in many modules that are connected together.
Windows itself is composed of several related modules. Windows API functions are implemented by several dynamic link library modules in the memory when Windows is started. The three main modules are user. EXE (for window management, etc.), kernel. EXE (multi-task scheduling for memory management) and GDI. EXE (graphical device interface, used for graphic output, etc ).

 

Note:Unless otherwise stated, the concepts are explained in Windows Programming basics-Overview.

Many of the contents in this Article refer to "Windows Programming basics-Overview", "in-depth introduction to MFC", and "VC ++ in-depth explanation". I would like to pay tribute to these three authors!

 

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.