Win32 study notes Chapter 3 Hellowin

zhaozj2021-02-16  46

Win32 learning notes

Author: Jiang Xuezhe (netsail0@163.net)

Textbook: Windows Program Design (Fifth Edition) Peking University Press [United States] Charles Petzold Translations from Beijing Boan Technology Development Co., Ltd.不 作者 不 编 工 出 社 社 社 社 工 社 社 出 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 社 译 译 译 张 张 张 张 张 译 译 译 译 译 译 译 译 译 译 译 译 ¥ ¥ ¥ ¥ ¥ ¥ 译 ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ ¥ Xu Kexi ¥: 42

Environment: Windows2000 PRO Internet Explorer 6.0 DirectX8.1 Visual C 6.0

Tint Jiang Computer Program Group (http://chulsoft.xiloo.com) Copyright, reprint, please explain the source ----------------------- ------------------------------------------- [Chapter 3 Hellion]

April 16 is a wish to commemorate. The main page is on the 16th day, our website access is 19500. We didn't do anything, and even the search engines were not submitted. So feeling very unexpected. How can there be so many people visit, how do visitors know our website? It's really incredible.

After the preparation of the first two chapters, we must officially see Win32 code. Before this, I assume that you have a knowledge of C language. If you don't have a knowledge of C, then take time learning. The focus of Chapter 3 is the Hellowin that started in the thirty-ninth page. Our all tasks are to understand it. It may be that I am particularly low. I have no patience. I chose to give up when I saw the third chapter a few months ago. At that time, I didn't understand it in this life. It is really awkward.

It is really difficult to talk to me. Because many new knowledge points are blank to me. There is no concept in mind, it is really a "one fogwater". Because I feel that Win32 is too difficult, I turned to C, which is the programming in the TC2 environment. I have learned it for a while, and I feel that TC2 is also very difficult. I also returned to Win32. I also know that this learning attitude is not good. Although I have turned to Win32 from TC2 to Win32, it is light, but this time I have to learn Win32, this will never be like a few times.

In fact, it is now thinking, I am abolishing, if I can understand it, I can understand it, and white is wasted so much time. So, if you think this program is too difficult, you must insist on reading more. The process is relatively boring. From the beginning you will encounter some difficulties, such as Win32 dedicated terms. Some terms have a simple meaning, but it is very difficult to explain.

We take a while to adapt. At the beginning, you will touch the "window process", "window" and other terms. Because there is no concept in your mind, it may produce despections of life when you see these terms. Please rare your life, strong, dealing with these terms is hard to read down. You can first mean the meaning. As long as you leave some impressions in your mind. After you understand the Hellown code, I will return to my head to re-read N, you will have an unexpected gain.

I am a farmer's origin! Coupled with IQ is not very high, reading can only use this stupid approach. This kind of thing has to rely on the day. Maybe you can understand it.

There may be a lot of doubts after you have finished reading the third chapter. A considerable part of them will be explained in Chapter 4. So when you see a doubt, you can skip the paragraph first when you have a detailed explanation. After learning the next few chapters, I went back and took a look. This is definitely not a waste of time. In order to learn Win32, I have thought about giving up the "Imperial Times" and "Star Bione", no! ! I don't give up! ! My favorite! Maybe as learning deeper these games will gradually go far away. Yes, don't know when you have 2 generations?

In the first two cases, MessageBox () is used to output text to the user. The MessageBox () function creates a message box window. The term "window" in Windows has an exact meaning. One window is a rectangular area on the screen. It receives the user's input and displays the output content in the format of text or graphics.

MessageBox () Creates a message box window, but this is just a special special window. This window has a title bar with a closed button, an optional icon, one line, or multi-line text, and up to 4 buttons.

Messagebox () although useful, we cannot display graphics in the message box, or you cannot add a menu in the message box. If you want to add these stuff, you need to create your own window and start now.

In the book, the creation window is simple, just call CREATEWINDOW (). In fact, Windows has made most things, and what we have to do is remember to remember the names and functions of the API function, and then move it in the actual development process. This seems to be very simple, but in fact, there are still many jobs that require programmers.

Although the part is done, it is still a good job. In addition, if your English level is going, you will have a lot of help to learn. Microsoft's MSDN is a very good stuff. Unfortunately, I won't look.

The WINDOWS program is designed, which is actually an object-oriented programming (OOP). Don't tell me that c does not support object-oriented, I don't know anything.

The most obvious window on the desktop is the application window. These windows contain the title bar, menu, toolbar, and scroll bar of the display program name. Decorative dialog covered also have a variety of buttons, radio boxes, check boxes, list boxes, scroll bars, and text input areas. These are all windows. More specifically, these are called "sub-windows", "control windows", "sub-window controls".

In fact, buttons are also a window. For example, the "Start" menu button of Windows, it is a window called "button window". If you have a scroll bar in C language without using a Windows API, it is also a difficulty of it is difficult to write. For rookies like us, write scroll bar functions, is not a happy thing. Very lucky is Windows already provided a large string ready-made scroll strip function.

When we move the mouse, when we knock on the keyboard, when we click on the mouse button ... when ... when ... is ..., a signal will result. This signal represents a certain operation. We can use a signal to indicate the movement of the mouse, and use another signal to indicate the press of the left mouse button, etc., and so on. Windows refers to this signal as "message".

This window will receive a "message" when the user clicks on a window. The window receives the input of the window in the "message" form, and the window also uses messages to communicate with other window. The understanding of the message will be one of the obstacles that learn to write Windows programs must be over. Very important! Although the news is not difficult to understand, it is indeed a very strange Dongdong.

Press a keyboard to generate a message, move the mouse to generate a message, click the left mouse button to generate a message ... In short, Windows is driven by the message. What is the news? I will probably understand after you understand the Hellowin program. I can only say, look at it a few times! !

We can drag the window border with the mouse to change the window size. The program changes the content in the window to respond to this change. Re-adjusting the window size is Windows processed. The application doesn't have this burden. The application is just to change the content of the window to respond to this change. How does the application know that the user changed the size of the window? There are many programmers who are accustomed to character mode. The operating system does not inform the application mechanism in the character mode. The key to the problem is to understand the architecture used by Windows. When the user changes the window size, Windows sends a message to the program, indicating the new size of the window. Then the program adjusts the content in the window to reflect the size of the size.

"Windows Send Messages". This is a bit badly understood for some people who have experience in character mode. How does the operating system send a message to the program? In fact, "Windows Send Messages" refers to a function in the Windows Call program that is designed to receive messages issued by Windows and users. This function called by the system is called a "window process" in this application.

We are very well understood by the application call operating system. For example, in DOS, the application is often called DOS interrupt. But the function in the operating system calling the application may be very uncomfortable. And this is the basis for the object-oriented architecture of Windows.

Each window created by the program has a related window process. The window process is a function. This function can be in the program or in the dynamic link library. Windows handles the message sent by the call window. The window process is processed according to this message and then returns the control to Windows.

The window is usually created on the basis of the window class. You will know what window classes when you read Hellowin. The window procedure for processing the message of the window is specified in the window class. Multiple windows can be based on the same window class and use the same window process. For example, all buttons in all Windows programs are based on the same window class. All Windows buttons we have ever seen use use a window process.

A message notification window is notified when the window size change or window surface needs to be sang. The message sent to the window is processed by the window process function of the window.

After the Windows program starts execution, Windows creates a "message team" for the program. This message queue is used to store a variety of different window messages created by the program. There is a small code in the program called "message loop" to remove messages from the queue and send them to the corresponding window process. Some messages are sent directly to the window process without placing in the message queue.

Although I have a bunch of SAY, you may still don't understand. It doesn't matter, let's take a look at the first WIN32 program. This is the focus of this chapter and is the real start of the entire Win32. This code is representative, you'd better be manually knocked a few times, this is absolutely necessary! Such a brain will leave some impressions. Don't be lazy ...

◎ page 39:

/ * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------ HelloWin.c - Displays "Hello, Windows 98!" In Client Area (C) Charles Petzold, 1998 --------------- -------------------------------------------- * /

#include

Lresult Callback WndProc (HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {static TCHAR szAppName [] = TEXT ( "HelloWin"); HWND hwnd; // window handle MSG msg; // message structure WNDCLASS wndclass; // Window class structure wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION); // load icon for The program uses WNDClass.hcursor = loadingcursor (null, idc_arrow); // Loading a mouse pointer for the program using WNDClass.hbrbackGround = (HBRUSH) getStockObject (White_brush); // Get a graphic object, in this example, is a drawing window background Brush wndclass.lpszMenuname = null; wndclass.lpszclassname = szappname;

If (! registerclass (& wndclass)) // Registered window class {MessageBox (NULL, TEXT (NULL, TEXT (NT! "), SZAPPNAME, MB_ICONERROR); RETURN 0;} // Create a window according to window classes hwnd = CreateWindow (szAppName, // window class name TEXT ( "The Hello Program"), // window caption WS_OVERLAPPEDWINDOW, // window style CW_USEDEFAULT, // initial x position CW_USEDEFAULT, // initial y position CW_USEDEFAULT, // initial x Size CW_USEDEFAULT, // Initial y size null, // window menu handle hinstance, // program instance handle null; // CREATION Parameters showwindow (hwnd, icmdshow); // Display window updateWindow (hwnd) on the screen; // Indicates the window to refresh your while (GetMessage (& MSG, NULL, 0, 0)) // Get a message from the message queue {TranslateMessage (& MSG); / / Convert some keyboard message DispatchMessage (& msg); // Send the message to the window} return msg.wparam;}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {HDC hdc; PAINTSTRUCT ps; RECT rect; switch (message) {case WM_CREATE: // play a sound file PlaySound (TEXT ( "HelloWin.wav") , NULL, SND_FILENAME | SND_ASYNC); RETURN 0; CASE WM_PAINT: HDC = BeginPaint (HWND, & PS); // Start window drawing getClientRect (hwnd, & rece); // Get the size of the window customer area DrawText (HDC, Text (" Hello, Windows 98! "), -1, & review, dt_singlex | DT_Center | DT_VCENTER); // Displays text string Endpaint (hwnd, & ps); // End window to draw Return 0; case wm_destroy: postquitmessage (0); //// Insert a "exit" message Return 0 in the message queue;} return defWindowProc (hwnd, message, wparam, lparam); // Execute the default message processing} ------------------------------------------------------------------ -------------------------------------------------- ---------- The entire program consists of two functions. WinMain () is the entrance of the program. WndProc () is the window process. The Windows system will call it.

WinMain () has WinAPI, which has never seen before. So I ran to the forum asked. Some people say that this is the order of the calling of the parameters. What does it mean? I really don't understand. But I know that it is defined in WINDEF.H as follows:

#define winapi __stdcall

There is a Callback in front of the window process function, and his definition is as follows:

#define callback __stdcall window The type of function is LRESULT, which is defined as follows:

Typedef long Lresult;

But please pay attention! Don't take

Lresult Callback WndProc (HWND HWND, UINT MESSAGE, WPARAM WPARAM, LPARAM LPARAM)

Write:

Long Callback WndProc (HWND HWND, UINT MESSAGE, WPARAM WPARAM, LPARAM LPARAM)

Although LRESULT is indeed a LONG, the format when the window process function is defined.

WPARAM LPARAM is Long

#define pascal pascal # Define Near Near # Define Far Far

typedef unsigned int UINT; typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; typedef long LONG; typedef char * PSTR; typedef char NEAR * NPSTR; typedef char FAR * LPSTRtypedef void VOID; typedef int * LPINT; typedef LONG (); Source code and hellowin sound files in the CD. Copy the entire hellowin into your hard drive and remove read-only properties. Then compile the running program. Be sure to remove the read-only properties.

The program creates an ordinary application window. Display "Hello, Windows98!" In the center of the window customer area. The Winmain () part of the program is representative, and n times will be repeated in many programs in the future, and it is almost unhappy. You will find that each program is different from the window procedure function section.

The Hellowin program shows the text string in the center of the window customer area. The client area is the free drawing of the program and delivers the window area of ​​the visual output. There is a large white area in the Hellowin program, which is the customer area.

Like other programs, the window created by the Hellowin can move and can change the window size. The upper right corner is "maximized", "minimize" and "off" button. Regardless of how the user changes window size, the program will automatically reposition "Hello, WinODWS98!" Text string in the center of the customer area. I will introduce the code that implements the above functions.

Hellowin called 18 functions. These 18 functions are Windows API functions. If you want to know the details of these 18 functions, you can check the Windows API Reference Manual. We must absolutely buy a reference for Windows APIs. If you have a good API reference manual, don't forget to tell me the title. If your English is very good, you can also see MSDN.

There are many uppercase identifiers in the program. These identifiers are defined in Windows's header files.

CS_HREDRAW DT_VCENTER SND_FILENAME CS_VREDREDRAW IDC_ARROW WM_CREATECW_USEDEFAULT IDI_APPLICATION WM_DESTROY DT_CENTER MB_ICONERROR WM_PAINT DT_SINGLINE SND_ASYNC WS_OVERLAPPEDWINDOW

The above is a simple numerical constant. The prefix of the identifier represents the category to which the constant belongs.

CS --- Class Style Option CW --- Create Window Options DT --- Draw Text Options Idi --- Icon ID Number IDC --- Cursor ID MB --- Message Box Option SND --- Sound Option WM - - Window Message WS --- Window Style

MSG - Message Structure WNDCLASS - Window Class Structure Paintstruct - Drawing Structure RECT - Rectangular Structure

Finally there are three uppercase identifiers for different types of "handles".

Hinstance - Example (Program Self) Handle HWND - Window Handle HDC - Device Description Table Handle

The handle is very frequent in Windows. It is also very important concept. We will also encounter an icon handle HICON, mouse pointer handle HCursor, graphical brush Hbrush. What is the handle?

Handle is a new data type. Menu, windows, icons, memory, devices, programs, bitmaps, etc. are called "objects". That is, the menu is a menu object, the window is a window object, and the memory is a memory object. For such a call, you must have habit. The handle can represent an object. We reference an object with your handle. For example, we can use the device description table handle to reference a device (such as a display). When we use a device description table handle to reference the display, the handle represents the display. We use this handle to use the display. ■ Common handle type

Handle ------------------ Universal handle type hWnd -------------------- Identify a window object HDC - ------------------- Identify a device object HMENU ------------------ Identify a menu object hic --- ----------------- Identify an icon object hcursor ---------------- Identify a cursor object Hbrush ------ ------------ Identify a brush object HPEN -------------------- Identify a pen object HFONT -------- ----------- Identify a font object hinstance --------------- Identify an instance of an application module Hlocal ---------- -------- Identify a local memory object hglobal ---------------- identify a global memory object

That is, hwnd represents a window object, and HDC represents a device object. This device is likely to be a memory, or it may be a disk. The handle is a number, usually 32 digits, expressed in hexadecimal form. Do you understand what I am talking about? do not understand? I may understand after reading this book, please stick to it.

The first group of variables encountered after entering the program.

Static tchar szappname [] = text ("hellowin"); hwnd hwnd; // window handle MSG msg; // message structure WNDCLASS WNDCLASS; // window class structure

The second variable is a window handle. It represents a window. So which window is it representative? I haven't assigned it yet, so which window doesn't mean.

Of course, if you are happy, the second variable can be defined:

HWnd aaa; // or: hwnd bbb;

Like INT, FLOAT, etc., the variable name can be casually. The following two are also the same:

MSG Addf; wndclass sdakd221;

First, you want to define the window class, which is assigned to the window structure. Window classes are just the definition window. SO, all window objects created based on this window include the feature given in the window class. Below we analyze every domain of the window class.

WNDCLASS.Style = CS_HREDRAW | CS_VREDRAW;

The above statement represents: Whenever the horizontal direction dimension (CS_HREDRAW) or vertical dimension (CS_VREDRAW) changes, it is fully refreshing (refresh is over the screen. All graphical interfaces we see are "painting "from.). No matter how you change the HelloN window size, we can see the text string "Hello Windows98!" Is still displayed in the center of the window, and the two identifiers ensure this.

WNDCLASS.LPFNWNDPROC = WNDPROC;

This statement specifies the window process function of this window class as WndProc (). All new windows created by this window will be treated as their own window process function. This is very important, you must remember!

WNDCLASS.CBCLSEXTRA = 0; the public data area of ​​the window object created based on the same window class. I don't quite understand what this means, I am a rookie. Look at the literal meaning is that all window objects created based on this window class will have a public memory area. Is my understanding correct? Is there a master to teach me?

Wndclass.cbWndextra = 0;

The current window object private data area size.

Wndclass.hinstance = Hinstance; // Current process object unsuccess

The handle of this program. That is, the handle of the Hellowin program. If you let me talk fine, it can be difficult for me. I am still a rookie! Maybe I will understand the whole book? This is one of the parameters of WinMain ().

WNDCLASS.HICON = LOADICON (NULL, IDI_APPLICATION);

Set an icon for all windows created based on this window class. This parameter should be set to an instance handle Hinstance of the program when you want to load your own icon. If you want to get a predefined icon handle, we can set the first parameter of LoadCon () to NULL. When the first parameter is NULL, the second parameter has the following options:

IDi_Application default application icon. You can look at Hellowin's look, that box is. IDI_ASTERISK asterisk IDI_EXCLAMATION 惊叹 IDI_HAND hand icon IDI_QUESTION Question mark IDI_WINLOGO Windows logo

The above identifier can be found in Winuser.h. The function returns the handle representing the icon object.

WNDCLASS.HCURSOR = loadingcursor (null, idc_arrow);

The loadcursor () function loads a predefined cursor and returns the handle of the cursor. The handle is assigned to the HCursor domain of the WNDCLASS structure. When the mouse passes through the "window created by this window", it becomes a small arrow. However, because the previous cursor is also a small arrow, we can't see the change in the cursor. Below is a predefined mouse pointer identifier:

IDC_APPSTARTING standard arrow Standard arrow and small hourglass IDC_ARROW IDC_CROSS cross IDC_HAND (Windows2000) hand IDC_HELP arrow and question mark IDC_IBEAM text I-IDC_ICON empty icon IDC_NO slash circle IDC_SIZE four-way arrow IDC_SIZEALL IDC_SIZENESW four-way arrow pointing northeast and southwest of the bi-directional arrow pointing IDC_SIZENS Nort-Pean two-way arrow idc_sizenwse points to the northwest and southeast two-way arrow idc_sizewe all the two-way arrow IDC_UPARROW vertical arrow IDC_WAIT hourglass

You can change the IDC_ARROW in the statement to other, then compile it once. Different results are seen when you move your mouse to the window. Try a try! ! You can try it first to pick up idc_cross.

Wndclass.hcursor = loadingcursor (null, idc_cross);

Then compile run once. Move your mouse to the top of the window, see what changes in the mouse? Is the mouse becomes a cross? The previous Loadicon () is also the same, you can try to change the second parameter. See what changes.

WNDCLASS.HBRBACKGROUND = getStockObject (White_brush);

Set the background color of the window object created based on this window class. HBR represents "Handle to a brush". The brush is a graphical term. Refers to the coloring pixel pattern for filling a region. Windows has several standard brushes, also known as a spare (STOCK) brush. The getStockObject () call shown above will return a handle of a white brush. The window customer area will be completely white. This is a kind of universal approach.

WNDCLASS.LPSZMENUNAME = NULL; Specifies the window class menu. Hellowin has no menu, so this is NULL.

Wndclass.lpszclassName = szappname;

Take the name of this window. I will recognize it in the future.

If (! registerclass (& wndclass)) // Registered window class for program window {MessageBox (Null, Text ("this Program Requires Windows NT!"), SZAPPNAME, MB_ICONERROR); RETURN 0;}

Create a window First you need to register a window class. The function of registerclass () is the registration window class. But the registration window class is not successful every time. So there should be a check-in mechanism.

RegisterClass () will return 0 after the registration fails. Therefore, when the window is registered after the failure is true, it is then performed MessageBox (). The result of executing Messagebox () is to display a message box and display "This Program Requires Windows NT!". Then exit the entire program. This English is probably that "this program needs Windows NT support!". If you are using Windows98, you may have a chance to see this message box when you run Hellowin.exe in the Act CD. I am win2k, so I can't see it. This message box appears indicates that the registration window failed.

The window class defines the general feature of the window, you can create many different windows using the same window class. Call CREATEWINDOW () Specify more detailed information about the window when creating a window.

Why can't a window have been specified by step? It is very convenient to separate these style information in this way. For example, all button windows can be created based on the same window classes. The window related to this window class is located inside Windows. All buttons work in the same way. But each button has different sizes, different screen positions, and different text strings. These different features are part of the CREATEWINDOW () definition instead of window class definition.

HWND = CREATEWINDOW (Szappname, // Specify a window class, based on the window class creation window text ("the hello program"), // This string will appear in the title bar WS_OVERLAPPEDWINDOW, // This window CW_USEDEFAULT, // The X coordinate of the window, more accurately is the X coordinate CW_USEDEFAULT, / / ​​window of the window on the upper left corner of the window CW_USEDEFAULT, / / ​​window of the width CW_USEDEFAULT, // window of the highness, // window Objects Father, NULL, // Venus handle or sub-window number Hinstance, // Current process instance handle NULL); // Window object's parameter pointer handle (I don't know what this means)

We have to pay attention to the third parameter ws_overlappedWindowwinUser.h definitions for WS_OVERLAPPDWindWindow as follows.

#define WS_OVERLAPPDWindow (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX)

What do you want to figure out this long strings? Very ... very ... very easy! This is the style of defining the window object. From the above statement, you can see that the real content of the third line is:

WS_OVERLAPTID | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX

The problem is that there is no explanation of the six WS_XXXX above what is used, so it can only be given by us.

Please change the third parameter ws_overlappdwindow:

WS_OVERLAPTID | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX

The next thing to do is to remove six WS_XXXX one one one one, then recompile it once every time, look at what the window will become. First remove WS_SYSMENU, that is, the third parameter is turned:

WS_OVERLAPPED | WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX

Then compile it, you will see your hellowin.exe in Lucky is already unless, the three buttons in the upper right corner of the window are invisible, the small icons in the upper left corner are not seen, and the system does not appear when using the mouse right click on the title bar. menu. From this we already know the meaning of WS_SYSMENU. Next, let's take a look at WS_MINIMIZEBOX, what is used by WS_Maximizebox, changed to the following, then compile

WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME

You will see only one button in the upper right corner, maximize, minimize the end of time and space ... With this type, you can try one.

Fourth, the fifth parameters are the X, Y coordinates of the window object on the screen, and accurately said the coordinates of the top left corner of the window object.

Sixth, the seventh parameters are the width and height of the window object.

The eighth parameter parent window handle. You don't know what the parent window is Dongdong? Ok, please open the Notepad program, press Ctrl O, will find a window, this window is always on the notebook, this window is a child window, and notepad is the parent window. OK? I still don't know? ................ Hellowin has no parent window, and there is no sub-window. So this is NULL.

Hellowin has no menu, so ninth item is also null.

Ter 10, writing is written, Hinstance is an instance handle of the program, that is, this handle represents the program itself. At the same time it is also one of the parameters of WinMain ().

Article 11, the parameter pointer handle of the window object. Is it dizzy if you see such a long name? I don't know the specific meaning sorry ...

CREATEWINDOW () Returns the handle of the created window that is stored in the variable hwnd. Each window in Windows has a handle, and the program has a handle to reference the window. Many Windows functions require HWND as a parameter, so Windows can know which window is for the function. If a program creates a number of windows, each window has a handle. The window handle is one of the most important handles handled by the Windows program.

In this way, the CREATEWINDOWS () call returns the window has been created. Windows has allocated a memory to save all information set during the creation window. But we still can't see the window on the screen. There are also two functions display windows. one is:

ShowWindow (hwnd, icmdshow);

HWND is the handle of a window object that has just created with createWindow. We have to take a look at the second parameter. This is also the fourth parameter of WinMain (), int type. So what is this? Come on Baby!

The second parameter has three constants available.

SW_SHOWNORMAL SW_SHOWMAXIMIZED SW_SHOWMINNOACTIVE

What are these use? ? ? Like last time, change the code! please

ShowWindow (hwnd, icmdshow);

Change to

ShowWindow (hwnd, sw_showmaximized) or showwindow (hwnd, sw_showminnoactive)

Run once you have Know. Although the name is showwindow (), we can't show to Hellowin's generated window. Because we need to rehab the screen, it is refreshed.

UpdateWindow (HWND);

The function of this function is to refresh the window. Now I can finally see the window.

While (GetMessage (& MSG, NULL, 0, 0) // Get Message {TranslateMessage (& MSG) from the message queue; // Convert some keyboard messages DISPATCHMESSAGE (& MSG); // Send the message to the window process}

Windows maintains a message queue for each program currently run. this point is very important. A message will happen when you click on the mouse or right, and a message will also occur when you have some buttons. In short, no matter what you do, you will generate a message. These messages will enter the message queue. GetMessage () is responsible for removing messages from the message queue.

TranslateMessage () The system generates a virtual key message (VK_TAB, etc.) when the button is keys. When the virtual key code is received, the function sends the corresponding WM_CHAR code to the application message queue. I don't understand the meaning. However, this stuff seems to be not very important. DispatchMessage () Sends a message from the application's message loop to the corresponding window process.

The news is incoming team and does not enter the team. The entry message is sent to the window process in order, just like queuing tickets. The priority that does not enter the team is relatively high, and can be sent directly to the window process. It is like leaders who don't have to be queued to buy a movie ticket. While loop processing is a message in the team.

The MSG variable is the structure type MSG, and the type MSG is defined in WinUser.h as follows:

TypeDef struct tagmsg {hwnd hwnd; / / The handle of the window object of the message is sent to the window process function, that is, the source of the message. UINT Message; // message identifier, that is, message content. The additional information of the WPARAM WPARAM; // is depends on the value of Message. The additional information of LPARAM LPARAM; // depends on the value of Message. DWORD TIME; // Send the message time. Point Pt; // Send the position of the mouse on the screen when sending a message. } MSG, * PMSG;

The Point data type is also a structure, which is defined in WINDEF.H as follows:

Typedef struct tagpoint {long x; long y;} Point, * ppoint;

The message loop starts with the getMessage () call, which removes a message from the message queue: GetMessage (& MSG, NULL, 0, 0);

Here we need to know getMessage (). Its prototype is:

GetMessage (lpmsg lpmsg, hwnd hwnd, uint WMSGFILTERMIN, UINT WMSGFILTERMAX);

GetMessage () Retrieves the message queue and puts the message in the MSG structure pointed to by LPMSG. Let's come to the four parameters of the function.

LPMSG -> Pointer HWND -> Receive the window handle of the message to the MSG structure. Typically set to NULL, retrieved the window message belonging to the current program and the message generated using the postthredMessage () call. Related to PostthredMessage () later. WMSGFILTERMIN -> The minimum message value of the retrieval. Under normal circumstances set to 0. WMSGFiltermax -> The maximum message value retrieved. If WMSGFILTERMIN and WMSGFILTERMAX are set to 0, all messages are retrieved. Under normal circumstances set to 0.

Return value BOOL type. Returns false when retrieving a WM_QUIT message, otherwise TRUE. The message should be continued until getMessage () returns false to exit the While loop, terminate the program.

It is preparative job before we discussed. Register the window class, create a window, then display the window on the screen, the program enters the message loop, remove a message from the message queue, then send the message to the corresponding window, WinMain () is only these . The actual movement of Hellowin is done in its window process WndProc (). When the user changes the size of the window, or moving the window, all of these messages are processed by the window process. So Hellown's learning focus is its window process WndProc (). Did not understand WndProc () is equal to no Hellowin. The window process function determines what displayed in the customer area of ​​the window, and how the window responds to user input.

The window process is just a function, so we can give it a name. The name of the window process in Hellowin is WndProc (). A Windows program can contain multiple window processes, but a window class can only have a window process.

The window process is always defined as the following form:

Lresult Callback WndProc (HWND HWND, UINT MESSAGE, WPARAM WPARAM, LPARAM LPARAM)

In addition to the function name, in addition to the window procedure, it is necessary to make it eliminated. Everyone can see that the four parameters of the window process are the same as the top four of the MSG structure. DispatchMessage () Sends a message from the application's message loop to the corresponding window process. Because the window process is used to receive messages, it is the same as the first four domains of the MSG structure.

The first parameter is the window handle. This handle represents a Hellowin window. because:

HWND = CREATEWINDOW (/ * here is omitted ... * /);

The return value of CREATEWINDOW () is the handle of the new window. The above statement assigns the handle of the new window to hwnd. So hwnd represents a Hellowin window. If there is no such parameter, the ghost knows which window of the window process is to process. The front has been mentioned because multiple windows use the same window process, so the first parameter will be used to handle the message issued by the window. Hellowin has only one window object. So the first parameter can only be hwnd.

The second parameter message is the content of the message, such as WM_CREATE. The WM_CREATE message is made in CreateWindow (). The last two parameters are 32-bit message parameters, which provides more information about the message. These parameters contain details of each message type. In general, the Windows programmer uses the Switch statement to handle the message received by the window. The window must return 0 after processing the message. All all messages that the window process will not be processed should be passed to DefWindowProc (). The value returned from DefWindowProc must be returned by the window process. This sentence may be a bit bad. You can look at the last statement of Hellown in the LOOK:

Return DefWindowProc (Hwnd, Message, WPARAM, LPARAM);

Do you understand now? I want to think about it. This should be very simple.

WndProc () only selects three messages in Hellown: WM_CREATE, WM_PAINT, WM_DESTROY. The structure of the window process is as follows:

Switch (Message) {Case WM_CREATE: [Processes WM_CREATE Messages] Return 0;

Case WM_PAINT: [Processing WM_PAINT Message] Return 0;

Case WM_DESTROY: [Processing WM_DESTROY Message] Return 0;}

Return DefWindowProc (Hwnd, Message, WPARAM, LPARAM);

Call DEFWINDOWPROC () to provide default processing for all messages that the window process is not processed, that is, all messages other than the above three messages are processed by defWindowProc (). This is very important.

Case WM_CREATE: // Play a sound file Plays (Text ("Hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC); Return 0;

The first message received by the window process ---- also the first message for WndProc () selection processing is ---- WM_CREATE. When Windows processes CREATEWINDOW () in WinMain (), WndProc () receives this message. More accurately, this WM_CREATE is sent by CreateWindow ().

When WM_CREATE is generated, Windows calls WndProc (), sets the first parameter of WndProc () to the window handle of the Hellowin window object. The second parameter is set to the WM_CREATE message. WndProc () returns control to Windows after WM_CREATE. Then Windows continues to perform the statements behind the CREATEWINDOW () in WinMain ().

When the window process is received in the Hellowin program, you will play hellowin.wav after receiving the WM_CREATE message. Used is Plays (). We can see that it can be used to play sound files from the name of the function.

Case WM_Paint: HDC = Beginpaint (HWND, & PS); // Start window draws getClientRect (hwnd, & respons); // Get the size of the window customer area DrawText (HDC, Text ("Hello, Windows 98!"), -1, & Rect, DT_SINGLINE | DT_CENTER | DT_VCENTER; // Displays text string Endpaint (hwnd, & ps); // End window to draw Return 0;

The second message processed by WndProc () is a WM_PAINT message. This message is very important in Windows programming. When the part or all of the window customer area becomes "invalid", it is necessary to "refresh", will be notified by this message. There have been new names in here - "invalid". How can the customer area become invalid? For example, suppose the coordinates of the Hellowin window are original (300, 400). The user uses the mouse to drag the window so that the coordinates of the window becomes (301, 400). Since the coordinates of the window have changed, this window must also be sang on the display. I have said that the graphical interface on the screen is drawn, which is a bitmap file (like BMP). The newly painted window coordinates are (301,400). The user uses the mouse to change the location of the window, so that the coordinates become (302, 400), this time the display will have to retain this window, and the newly painted window coordinate is of course (302, 400). All this is a moment.

When the content displayed on the display is outdated, when you need to redraw, this time you say that the customer area of ​​the window becomes "invalid". Windows must be reset to the display window to meet the new location.

The entire client area is invalid when the window is originally created. Because the program does not draw any stuff on the display. This function issues the first WM_Paint message when the program is running to UpdateWindow ().

Processing for WM_Paint messs is almost always from a beginpaint () call:

HDC = BeginPaint (HWND, & PS);

End with an endpaint () call:

Endpaint (hwnd, & ps);

If the customer area background is not deleted in BeginPaint () call, Windows will be deleted. It removes the background using the brush specified in the Wndclass.hbrbackground domain of the registration window class. This is a white spare brush in Hellown. So Windows will set the window background to white. BeginPaint () call makes the entire client area valid and returns a "device description table handle". Device Description Table Handle refers to a physical output device. For example, a display or a printer. The client area of ​​the window displays text and graphics requires device description table. You cannot use beginpaint () to draw the table handle outside the client area. Want to draw the device descriptor handle that needs other functions outside the customer zone.

Endpaint () Release the device description table handle so that the device description form handle is no longer valid.

The client area becomes invalid after the user changes the size of the Hellowin. Readers should still remember setting to flags CS_HREDRAW and CS_VREDRAW in WNDCLASS.Style domain, which indicates that Windows makes the entire window when the window size changes. Then the window process receives a WM_PAINT message.

Windows does not save a window that is covered by another window when moving the window overlap each other. When the portion originally covered is also exposed, it is marked as invalid, the window process receives a WM_PAINT message to refresh the contents of the window.

WndProc () then calls getClientRect () after calling beginpaint ().

GetClientRect (HWND, & Re); // Get the size of the window customer area

The function of the function is to get the size of the window client area. The first parameter is the handle of the program window, the second parameter is a pointer, pointing to a RECT type Rect structure. This structure has four long domains, which are Left, Top, Right, Bottom. These four domains are used to save the size of the window client area. The LEFT and TOP fields are typically set to 0, and the Right and Bottom domain are set to the width and height of the customer area (the unit is a pixel point).

DrawText (HDC, TEXT ("HLLO, Windows 98!"), -1, & review, dt_singlex | DT_Center | DT_VCENTER; // Displays the text string written into formatted text in the specified rectangle, according to the specified method text format.

The first parameter is the device description table. The second parameter is the text string displayed in the center of the customer area. The third parameter is -1, indicating that the text string displayed in the client area is ended with '/ 0'.

The size and location of the fourth parameter client area. Indicates that formatted text is displayed in this rectangle.

The fifth parameters:

DT_SINGLINE indicates that the text string must be displayed in the same line. Even if it is inserted into the carriage return and the newline, it cannot be folded. Dt_center represents the text string in the customer area level. DT_VCENTER represents the text string in the client area vertically. DT_SINGLINE must be specified while using this flag.

Once the customer area is invalid, WndProc () receives a new WM_PAINT message. WndProc () is used to get the changed window size by calling getClientRect () and use DrawText () to display text in the center.

The WM_DESTROY message is another important message. This message indicates that Windows is clearing the window according to the command input by the user. This message is that the user clicks the "Close" button or when selecting "Off" on the system menu of the program.

Hellowin responds to WM_DESTROY messages by calling postquitMessage ().

PostquitMessage (0);

This function is inserted into a WM_Quit message in the program's message queue. Previously, getMessage () returns a non-0 value for all messages removed from the message queue except for WM_QUIT. And when getMessage () is taken to a WM_QUIT message it returns 0. This will cause WinMain () to exit the message loop and terminate the program. Then the program executes the following statement:

Return msg.wparam;

I don't know the meaning of returning Msg.wParam at this time, I will understand later. In short, the entire program is over. I finally relaxed, the next content is a summary of the third chapter.

Even with the description of Hellown, the reader may still feel mysterious about the structure and principles of the program. When writing a simple C program for traditional environments, the entire program may be included in main (), and WinMain in Hellown contains only the registration window class, create a window, remove the message from the message queue and send the message. .

All actual actions of the program occurred during the window. These actions in Hellowin are not much. WndProc () just simply playing a sound file and displays a text string in the window.

In the later chapter, the reader will find that everything done by the Windows program is a message sent to the window procedure. This is one of the concepts of conceptual difficulties, and must first understand before starting writing a Windows program.

Programmers have been accustomed to using the idea of ​​operating system calls. For example, a C programmer opens a file using fopen (). FOPEN () ultimately opened the file by calling the operating system, this is undoubted.

But Windows is different, although Windows has more than 1,000 functions for program calls, but Windows also calls the user program. For example, the window procedure WndProc () defined earlier. The window process is associated with a window class, and the window class is registration registration registerclass (). All windows created based on the window class use the window procedure to process all messages.

When the first creating a window, Windows calls WndProc (), the window is canceled when Windows calls WndProc (), window change sizes, moves or turns icons, selects a certain item from the menu, scroll scroll bar, press the mouse or from When the keyboard input characters, and the window customer area must be refreshed with WNDPROC ().

All of these WndProc () calls are done in the form of messages. The main part of the program in most Windows programs is used to process messages. The message sent to the window process is usually identified by the name of the WM header and is defined in the Winuser.h header file. The Windows program has a message loop. It uses GetMessage to remove messages from the message queue and call DISPATCHMESSAGE () to send messages to the window process.

Is the Windows program sends a message to the window process in order? Or do you receive messages directly from the program? In fact, these two situations exist. The news is divided into "enter the team" and "not enter the team". The message of the team is Windows placed in the message queue. The message queued in the message queue of the program was taken out by GetMessage () and transferred to the window process. Messages that do not enter the team are sent directly to the window during the Windows call window. That is to say "Enter the team" message is sent to the message queue, "Do not enter the team" message sent to the window process. In any case, the window process will get all the messages of the window - including the entry and not enter the team. The window process is the "Message Center" of the window.

The entry message is basically the result of the user input, hit the key (such as WM_KeyDown and WM_KEYUP), the character (WM_CHAR) generated by the keystroke (WM_CHAR), the mouse movement (WM_MouseMove) and the mouse button (WM_LButtondown) are given. The corning message also includes a clock message (WM_TIMER), refresh the message (WM_Paint), exits the message (WM_QUIT).

Do not enter the teams often come from a particular Windows function. For example, when WinMain () calls CREATEWINDOW (), Windows will send a WM_CREATE message. When WinMain () calls showWindow (), Windows will send WM_SIZE and WM_SHOWWINDOW messages to the window.

This process is very complicated, very lucky is that most of them are solved by Windows, not too critical. When I saw the content of the fourth chapter, I found that the third chapter was simply a pediatric. The Hellowin in Chapter 3 is just ready to move.

转载请注明原文地址:https://www.9cbs.com/read-27629.html

New Post(0)