Chapter Three window in the message
The previous example uses the MessageBox to create the window, and the window he creates is limited in flexibility.
3.1 Creation of Windows
Just call the CreateWindow function to
3.1.1 System Structure Overview
An application window may contain, title bar, menu bar, toolbar, scroll bar. Another type of window is a dialog box, which can be used without a title bar
It may also contain, buttons, radio buttons, checkboxes, list boxes, scroll bars, text boxes, and so on. Each of these objects is called a child window, or a control window
When the user changes the window size, Windows sends a message to the application about the size of the new window, and the application adjusts its content to reflect the change in window size.
"Windows sends a message to the application", Windows calls a function inside the program---This function is written by you and is the core of the entire program. The parameters of this function are described by the Windows
The specific message that is sent by your program. This function is called a "window procedure". Windows calls this function of the application, which is the basis of the formal Windows architecture.
Each window created by the application has a window procedure corresponding to it. Can be a function in an application, or it can be a function in a DLL library. The window procedure handles these messages accordingly, and then returns control to the Windows
More precisely, Windows always depend on the window class to create. The window class identifies the window procedure for handling messages passed to the window. Multiple windows can share a window class, using the same window procedure.
When a Windows program is created, Windows first creates a message queue for the program. The message queue holds messages for all windows that the application may create. Windows applications typically contain code for a small piece of message loops that retrieve information from the message queue and distribute it to the window procedure.
Examples of Windows, window classes, window procedures, message queues, message loops, and window messages integrated into real-world applications
3.1.2
Need to load Winmm.lib in project Use PlaySound API function, disable in VS2015
#include <windows.h>lresult CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); Window Procedure.int WINAPI WinMain (hinstance hinstance, hinstance hprevinstance,pstr szcmdline, int icmdshow) { Statictchar szappname[] = TEXT ("Hellowin"); Hwndhwnd; msgmsg; wndclasswndclass;//the Window classwndclass.style= Cs_hredraw | Cs_vredraw;wndclass.lpfnwndproc<span style= "White-space:pre" ></span>= WndProc;//Assign the window Procedure to Windows class.wndclass.cbclsextra= 0;wndclass.cbwndextra= 0;wndclass.hinstance= hinstance; Wndclass.hicon= LoadIcon (null, idi_application); wndclass.hcursor= loadcursor (null, idc_arrow); Wndclass.hbrbackground<span style= "White-space:pre" ></span>= (hbrush) GetStockObject (WHITE_BRUSH); Wndclass.lpszmenuname<span style= "White-space:pre" ></span>= null;wndclass.lpszclassname<span style = "White-space:pre" ></span>= szappname;//register the window Class to the Windows System. if (! RegisterClass (&wndclass)) {MessageBox (NULL, TEXT ("This program require Windows nt!"), Szappname, mb_iconerror); return 0;} This function would generate an wm_create Message.hwnd = CreateWindow (Szappname,//window class Nametext ("The Hello Progra M "),//window captionws_overlappedwindow,//window stylecw_usedefault,//initial x positioncw_usedefault,//initial y positioncw_usedefault,//initial x sizecw_usedefault,//initial y sizenull,//parent window handleNULL,//window menu Handlehinstance,//program instance handlenull);//creation Parametersshowwindow (hwnd, icmdshow); UpdateWindow (HWND);//this function would generate a WM_PAINT message./* the message loop for this program.if received the W M_quit message, the function would return 0.*/while (GetMessage (&msg, NULL, 0, 0)) {translatemessage (&msg);D Ispatchmessage (&msg);} return Msg.wparam;} Define the Window Procedure wndproclresult CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {Hdchd C Paintstructps; Rectrect;switch (message)//get the Message{case Wm_create:plaYsound (TEXT ("Hellowin.wav"), NULL, Snd_filename | Snd_async); return 0;case WM_PAINT:HDC = BeginPaint (hwnd, &PS); GetClientRect (hwnd, &rect);D Rawtext (hdc, TEXT ("Hello, Windows 7 x64 Ultimate sercice Pack 1!"),-1, &rect,dt_sing Leline | Dt_center | Dt_vcenter); EndPaint (hwnd, &PS); return 0;case wm_destroy:postquitmessage (0); return 0;} Return DefWindowProc (HWND, message, WParam, LParam);}
3.1.3 Overall consideration
Virtually any Windows program has a structure similar to Hellowin.cpp. No need to remember all the details of this framework
The program includes a WinMain function (program entry) WndProc function (window procedure wind prock) there is no code called WinProc in Hellowin.cpp, but there is a reference to WinMain in WinProc.
Windows function calls
LoadIcon load icon for program use
LoadCursor loading the cursor for use by the program
Getstockobject get a Graphical object
RegisterClass Registering a window class for the application's window
MessageBox Display message box
CreateWindow Creating a window based on a window class
ShowWindow displaying windows in the screen
UpdateWindow instructs the window to redraw itself
GetMessage getting messages from Message Queuing
TranslateMessage translating some keyboard messages
DispatchMessage sending a message to a window procedure (WNDPROC)
PlaySound playing sound files
BeginPaint indicates that the window drawing begins
GetClientRect Get window client area dimensions
DrawText displaying a text string
EndPaint End window Drawing
PostQuitMessage inserting an exit message into a message queue
DefWindowProc performing the default message handling
Subscript for some commonly used Wnidow definitions
New data types
A lot of things to be compatible with some typedef or # define defined by different Windows versions
UINT unsigned int
WPARAM uint_ptr
LPARAM long_ptr
LRESULT LONG
Hellowin uses 4 kinds of data structures
MSG Message structure
Wndclass window class structure
Paintstruct Drawing structure
Rect Rectangle structure
Handle
HINSTANCE Strength Handle-Program itself
HWND Window handle
HDC Device Environment handle
Hungarian Labeling Act
To commemorate the Microsoft programmer Charles Simonyi variable name to indicate that the variable data type of the lowercase letter starts with the corresponding name
3.1.4 Window class Registration
Windows are always created based on the window class, and the window class determines the window procedure for processing messages (WNDPROC)
ASCII version
typedef struct TAGWNDCLASSA { UINT style; WNDPROC Lpfnwndproc; int Cbclsextra; int Cbwndextra; HInstance hinstance; Hicon Hicon; Hcursor hcursor; Hbrush Hbrbackground; LPCSTR Lpszmenuname; LPCSTR lpszClassName;} Wndclassa, *pwndclassa, near *npwndclassa, far *lpwndclassa;
Use WNDCLASS to create a WNDCLASS class and initialize a member, and then call the RegisterClass function to register
The most important is lpfnwndproc (the address of the window procedure) and lpszClassName (the name of the window class, usually the same as the main window)
Wndclass.style = Cs_hredraw | Cs_vredraw;
Specifies that all windows that are based on the window's class will be redrawn whenever the window's horizontal dimension (Cs_hredraw) or vertical dimension (Cs_vredraw) is changed.
Wndclass.lpfnwndproc = WndProc;
Set the window class's procedure to the WndProc function
Wndclass.cbclsextra= 0;
Wndclass.cbwndextra= 0;
Set aside some extra space in the class structure and in the window structure maintained by Windows, which is not used in this case 0
Wndclass.hinstance = hinstance;
Instance handle of the application
Wndclass.hicon = LoadIcon (NULL, idi_application);
Set an icon for a window based on the window class
Wndclass.hcursor = LoadCursor (NULL, Idc_arrow);
Set a mouse pointer for a window based on the window class
Wndclass.hbrbackground = (hbrush) getstockobject (White_brush);
Sets the background color for the client area of the window class, HBR represents a handle to the brush, which is set to white.
Wndclass.lpszmenuname = NULL;
With no menu bar
Wndclass.lpszclassname = szappname;
Name of the window class
GetLastError can get the cause of the RegisterClass return error, and the various API documentation indicates whether GetLastError can be used to get the error message.
Some programmers like to check the return value of each function call to determine if there is an error, which is meaningful.
hPrevInstance indicates that there are no old instances running in memory.
3.1.5 Window creation
The window class defines only the general characteristics of the window and uses CreateWindow to create a window
hwnd = CreateWindow (Szappname,//window class Nametext ("The Hello Program"),//window captionws_overlappedwindow,// Window stylecw_usedefault,//initial x positioncw_usedefault,//initial y positioncw_usedefault,//initial x sizeCW_ Usedefault,//initial y sizenull,//parent window handlenull,//window menu handlehinstance,//program instance HandleNULL ); Creation parameters
Szappname the window class you just registered, connect to the window class you just registered with the window class name
When the new window is a top-level window, the parent handle parameter should be set to NULL
CreateWindow returns the handle to the Creation window HWND (handle to window)
Display of the 3.1.6 window
When the CreateWindow call returns, the window is already created inside Windows (allocating memory), but you also need to call ShowWindow (hwnd, icmdshow) to display the window
Icmdshow sw_shownormal Normal display sw_showmaximized maximize sw_showminnoactive minimize to the taskbar
UpdateWindow (HWND); Redraw the client area of the window like the WndProc function sends a WM_PAINT message
3.1.7 message loop
After UpdateWindow, the new window is completely visible on the screen, and the program must be able to accept a variety of keyboard input and mouse input from the user. Windows maintains a message queue for every Windows program that is currently running on it, and Windows automatically converts these events to "messages" when an input event occurs.
while (GetMessage (&msg, NULL, 0, 0)) {translatemessage (&msg);D ispatchmessage (&msg);}
Message loops
typedef struct TAGMSG { hwnd hwnd;//The Handle of the window to which the message is directed UINT a message ;//Messages identifier WPARAM WPARAM;//32bit Message parameters, depending on the specific message LPARAM LPARAM;//Another 32bit message parameter, also depending on the specific message DWORD time;//message enters the message queue when point Pt The position coordinates of the mouse pointer when the message enters the message queue #ifdef _MAC DWORD lprivate; #endif} MSG, *pmsg, near *npmsg, far *lpmsg;
If the message captured in the message queue is not wm_quit, the GetMessage return value is not 0, otherwise 0 is returned
TranslateMessage (&MSG) will return the message to Windows for some keyboard message conversions, which can be removed if the application does not support keyboard input.
DispatchMessage (&msg) returns the message to Windows again, and then Windows sends the message to the appropriate window for processing. This is WndProc.
3.1.8 window procedure
Registers the window class, creates the window, displays the window in the screen, the program enters the message loop, and retrieves the message from the message queue.
A really meaningful thing happens in a window process.
A Windows program can contain multiple window procedures, and a single window procedure is always associated with a particular window class registered by RegisterClass.
CreateWindow Create a window based on a particular window class, a window class can create multiple windows
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM);
HWND window handle for receiving messages
Message type
WParam, LParam Extended Message
If you need to call a window function, you can use the SendMessage function
3.1.9 Message Processing
Using the SWITCH-CASE structure, processing returns 0, the window procedure does not process the message that needs to be passed to DefWindowProc processing and returns the value returned to the current window procedure
It is important to process messages with DefWindowProc, otherwise the application's normal functionality cannot be
3.1.10 sound file playback
After the call to the CreateWindow function, Windows completes the necessary operations, Windows calls WndProc, sets its first argument to the current window handle, and the second argument to Wm_create.
The WndProc then processes the WM_CREATE message and returns control to Windows. Then Windows returns to Hellowin from the CreateWindow call
Typically a one-time initialization of a window in Wm_create, the example plays a WAV file called the PlaySound function
3.1.11 WM_PAINT News
When some or all of the customer's areas are invalid and must be updated, the application will get this notification, which means that the window needs to be redrawn.
The first WM_PAINT message is sent by UpdateWindow in WinMain.
Changing the window size or minimizing the response will redraw the customer area. or window Overlay
Processing of WM_PAINT messages almost always starts with calling the Begnpaint function
HDC = BeginPaint (hwnd, &PS);
GetClientRect (hwnd, &rect); //Get rect for the customer area
DrawText (HDC, TEXT ("Hello, Windows 7 x64 Ultimate sercice Pack 1!"),-1, &rect,
Dt_singleline | Dt_center | Dt_vcenter);
EndPaint (hwnd, &PS);
Device environment refers to physical output devices and their device drivers
EndPaint frees the device environment handle to invalidate it.
DrawText draws text, although DrawText looks like a GDI function, but he belongs to a fairly high-level module
The last parameter sets some typographic parameters for drawing text
3.1.12 Wm_destroy News
Indicates that Windows is in the process of destroying Windows according to user commands
The standard response method is to call PostQuitMessage (0); A wm_quit is inserted into the message queue, and then GetMessage receives a WM_QUIT message that returns 0 and exits the message loop. Then the program returns
return msg.wparam;
Some difficulties in 3.2 windows programming
Although the Registration window class is made, the window is created, the window is displayed, the Update window is updated, and the message loop. But the really meaningful process is in the window.
3.2.1 Exactly who calls who
In Windows programs, the operating system can invoke the user's function WndProc
WndProc is called in a similar scenario, when a window is destroyed, the window size is sent or minimized, etc., when the user performs a click in the window or a double-click operation. When you enter text with the keyboard, when the user selects an option from the menu, the customer area needs to be redrawn, and so on.
All calls to WndProc occur in the form of a message. Then WndProc process the corresponding message or give it to defwindowsproc for processing.
3.2.1 Queue messages and non-queue messages
A queue message is a message that is placed by Windows into a program's message queue and then retrieved by the program's message loop and called by the window function Post thread async
A non-queue message is generated by a direct call to a window function. Send thread Synchronization
Regardless of whether the queue window procedure is processed, the window procedure is actually the "message Center" of the window
Queue messages are mainly generated by the user input, mainly keystrokes, mouse and other operations, as well as timer messages, redraw messages, exit messages and so on.
Non-queue messages are caused by specific Windows functions such as CreateWindow (Wm_create), ShowWindow (Wm_size, Wm_showwindow), UpdateWindow (WM_PAINT)
Message Queuing for each thread is message processing only for Windows that the window procedure executes within that thread. Message Queuing and window procedures are not concurrent, and the DispatchMessage function will not return until the window procedure returns.
A window procedure can call a function that sends additional messages to it. The window procedure is reentrant
"Windows Programming" reading pen three window with message