Windows programming's Fifth Review of GDI

Source: Internet
Author: User
Tags textout

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

Finally met again

After a while, I finally met you again. I have been a little busy recently and have not seen a movie for weeks. But I like this feeling, which makes me feel full and clear. Recently, I like writing things, because whenever I write a pen or use a code word on the keyboard, I can calm down my impetuous mind to learn and think. I can't read any books that I can read. I always rely on Reading Notes to force myself to read books. I feel that this method is good. If you can't read books or feel impetuous, you can try it. Whether you like it or not, read more books. What is a saying? When books are used, they hate less!

GDI? What's sacred?

GDI is short for Graphics Device Interface (Graphic device interface). When a Windows application needs to display vertices, lines, images, text, and other content, It outputs the content on a display or printer, you need to use GDI. Graphical device interfaces are the basis of the Windows GUI. As you think, GDI is a very important part of windows. Of course, GDI is not the only programming interface that can implement this function. GDI is only the most basic of it. In addition to GDI, you can also implement similar or more advanced functions such as GDI +, OpenGL, DirectX, and Windows Image Acquisition.

The significance of GDI is to isolate program operations on graphical interfaces from hardware devices, that is, to support devices-independent graphics. In a program, all graphical devices can be considered as virtual devices, including video monitors and printers, and then operate them in the same way through the GDI function. Windows is responsible for converting function calls to specific hardware operations. As long as a device provides drivers compatible with windows, it can be seen as a standard device. With the advent of GDI, programmers can convert the output of applications into outputs on hardware devices without having to care about hardware devices and device drivers, thus realizing the isolation between program developers and hardware devices, this greatly facilitates development.

ExploringGDI

From the programmer's point of view, GDI consists of many function calls and related data types, macros, and structures. Unfortunately, if you want to fully describe GDI, you will need a large book. For this reason, we can briefly understand the GDI operations in three aspects: when, where, and how:

When -- refers to the timing of graphic operations. At what time is it best for a program to perform graphic operations?

Where -- refers to where the image should be drawn. Since windows isolates hardware graphics devices, what should we use as the "Next" place?

How -- after learning about the above two questions, I also need to know "how to draw", which involves how to use most of the GDI functions.

1. When -- wm_paint message

1. Refresh the customer Zone

As mentioned above, the question "when" is discussed here. The reader may ask: why is this question? If you want to output a graph to the window, when does the program want to output data? Is there a rule at this time?

Yes, in a Windows operating system, the screen is "public" by multiple programs. user programs do not expect to keep the content in the window after a period of time, they may be overwritten by other things, such as other windows, mouse arrows, or drop-down menus. In Windows, most of the responsibilities for restoring covered content belong to the user program. The reason is simple: Windows is a multi-task operating system. If program B overwrites the window content of program, if the overwritten content is restored by program B, it must save the content it overwrites, but before it restores the saved content, program A is also running, it is also possible that new content has been output to its own window before program B recovers. As a result, when program B restores the window content it saves, the saved content may be out of date.

Windows uses the following method: when Windows detects that the window is overwritten and needs to be restored, it sends a wm_paint message to the user program, then, the user program determines how to restore the covered content.

If the program cannot respond to the wm_paint message in a timely manner because it is busy processing other transactions, windows may temporarily draw a white (or background color) rectangle in the original coverage area of the window customer area, or it is simply to keep the case when it is overwritten until the program has time to respond to the wm_paint message.

Therefore, the answer to the question "when" is: The program should draw the customer zone as required by windows, that is, when receiving the wm_paint message. To process the wm_paint message, the programmer is required to change the way of thinking that he/she outputs to the display. The program is drawn only when Windows sends the wm_paint message to the window process. If the program needs to update its customer zone at other times, it can force windows to generate a wm_paint message (for example, a wm_paint message can be triggered by calling functions such as invalidaterect ). This seems to be a way to show content on the screen, but please believe that your program structure will benefit from it.

2. When will the system send the wm_paint message?

Most Windows programs call the updatewindow function during initialization before entering the message loop in winmain. Windows uses this opportunity to send the first wm_paint message to the window process. This message Notification Window process: the customer area must be drawn.

Afterwards, the window process should be prepared to process other wm_paint messages at any time, and, if necessary, re-draw the entire customer area of the window. Of course, Windows does not send the wm_paint message in any situation. The following are several different cases:

When the mouse and cursor move over the client area of the window and the icon drag over the client area, windows always saves the covered area and restores it, you do not need to send the wm_paint message to notify the user program.

Ii. When the window client area is overwritten by its own drop-down menu, or is overwritten by its pop-up dialog box and message box, Windows will try to save the covered area and restore it later, if it cannot be saved and restored for some reason, Windows will send a wm_paint Message notification program.

Iii. When a user moves a window or displays a window, the hidden area in the window is re-visible. For example, if another window overwrites the client area, the window is removed or the program is restored from the minimized state; the user changes the window size (if the window class style has cs_hredraw and cs_vredraw settings), the user presses the scroll bar, and the program calls functions such as updatewindow, invalidaterect, and invalidatergn. In these cases, Windows sends the wm_paint message to the window.

3. invalid and valid rectangles

Although the window process is ready to update the entire customer area after receiving the wm_paint message, it often only needs to update a small area (the most common is the rectangular area in the customer area ). Obviously, this is the case when the dialog box overwrites some customer zones. After the erase dialog box, you need to re-draw the rectangular area covered by the previous dialog box. This region is called "invalid region" or "Update region ". Only when an invalid region exists in the customer zone will windows put a wm_paint message in the message queue of the application. Only a part of the customer ZoneInvalidThe window will receive the wm_paint message. (It can be seen that "invalid" is the root cause of wm_paint messages)

In Windows, a "Drawing Information Structure" is saved for each window. ① this structure contains the coordinates of the smallest rectangle surrounding the invalid area and other information. This rectangle is called an "invalid rectangle ". If another area in the customer area becomes invalid before the window process processes the wm_paint message, Windows calculates a new invalid area (and a new invalid rectangle) that is surrounded by two areas ), and put the changed information in the above-mentioned drawing information structure. Windows does not place multiple wm_paint messages in the message queue.

During the window process, you can call invalidaterect to invalidate the rectangle in the customer zone. If a Message Queue contains a wm_paint message, Windows calculates an invalid rectangle. Otherwise, it puts a new wm_paint message into the message queue.

 

2. Where-device context (DC)

After solving the "when" problem, consider the "where" problem. In Windows, GDI separates the program and hardware, so where should we output the image? This is the "where" problem. The answer is: "device description table" is used to output images.

What is a device description table?

In Windows, all graphic-related operations are completed in a unified way (otherwise, they cannot be called "graphic device interfaces ). Whether it is a window on the screen, the graphic output to the printer, or the drawing of a bitmap, the use of the drawing functions are the same, in order to achieve unified methods, all graphical objects must be considered as virtual devices that may have different properties, such as the color depth of a black-and-white printer and a color screen, the sizes and resolutions of different printers may be different. The plotter only supports vectors but not bitmaps. Different properties of different devices constitute the "Environment" of a drawing. The "environment" of this drawing is the graphic operation object in Win32 programming. It is called the device description table ②. The device description table is also called the device context or the device environment.

In a Windows application, the device description table works together with the graphic object to complete the drawing display. Like a painter's painting, a device description table is like a painter's canvas, and a graphic object is like a painter's paint brush. Paint with a paint brush on the canvas. Different paint brushes draw different pictures. Select an appropriate Drawing Object and Drawing Object to complete the drawing task as required.

In actual use, the device description table can be used to operate on a wide range of objects, in addition to the printer, plotter, and other hardware devices, or the customer area of the window, it includes all the customer zones, including buttons and controls that can be called windows, large and small. It can also be a bitmap. In short, any things that require graphic operations can be drawn through the device description table.

Iii. How -- See the example

After you have a preliminary understanding of the above two questions, let's finally look at the "how" question. There are quite a few GDI functions, and they can be used to write a thick book. Of course, we do not need to involve every function. Next we will discuss some common GDI functions. Now let's solve the "historical issues ".

Let's take a look at a simple text display example:

62 case wm_paint:
63 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;

Familiar with this, this is part of the second Code. Its function is to display "Hello World!" in the upper left corner of the window client area! ", I have never said this, just to wait till now to let you know.

Row 63 defines a device description table handle variable HDC, and row 64 defines a "Drawing Information Structure" variable mentioned above, row 65 assigns the handle of the applied device description table to the variable HDC. Row 66 indicates that we can operate on the requested "environment, that is, in the screen window, the customer outputs the text, and row 67 releases the device description table handle.

Through this example, we can better understandDevice description table, only"Environment"Instead ofDevice", This"Environment"AndSpecific display devices (displays in this example. We only express what we want to do in this "environment" (for example, we want to output the text "Hello world! "), How to let the devices (monitors) Do the specific" environment "? This is the system thing. We don't care. Isn't this simplifying the programmer's work.

 

Additionally, some values in the device description table are graphical "attributes" that define some special aspects of the operation of the GDI drawing function. For example, for textout (HDC, X, Y, pstext, ilength ), the properties of the device description table determine the text color, text background color, and how the X and Y coordinates of the textout function map to the customer area of the window, and the font used by windows to display text. In fact, the device description table is actually a data structure, and the structure stores the properties of the device. When you perform graphical operations on the device description table, windows can find the corresponding device based on these properties for related operations.

 

This example also tells us that when you want to draw a picture on an image output device (such as a screen or printer), you must first obtain a device description table (or DC). After obtaining the handle, Windows fills in the internal device description table structure with the default property value. As you will see later, you can change these default values by calling different GDI functions. Other GDI functions can be used to obtain the current values of these attributes. Of course, there are other GDI functions that can be truly drawn. Next, we call the GDI function to plot the current device description table to complete our task. After drawing, you must release the device description table handle. After the handle is released, it is no longer valid and cannot be used. The program must obtain and release the handle during processing a single message.
Maybe you are disgusted with this series of tedious operations. I suggest you endure it. Since you enjoy the convenience provided by Windows, you must follow its "rules" unconditionally ".

 

After reading this question, I want to know about the "how" problem. We have basically completed the tasks of the GDI module from three aspects. You can relax. Let's see you next time.

 

① Windows saves a "Drawing Information Structure" for each window, which is paintstruct, which is defined as follows:

Typedef struct tagpaintstruct {

HDC;

Bool ferase;

Rect rcpaint;

Bool frestore;

Bool fincupdate;

Byte rgbreserved [32];

  } PAINTSTRUCT, *PPAINTSTRUCT;         

When the program calls beginpaint (next lecture), Windows will properly fill in the values of each field in the structure. The user program only uses the first three fields. Other fields are used in windows.

The HDC field is the handle of the device description table.

The ferase field records whether Windows has erased the background of the invalid rectangle. In most cases, if it is marked as false (0), this means that Windows has erased the background of the invalid rectangle. (Windows uses the image brush specified by the hbrbackground field in the wndclass structure to erase the background. This wndclass structure is used by the program to log on to the window class during winmain initialization. Many Windows programs use white paint brushes. The following statements show the class structure fields of the program settings window:

wndcls.hbrBackground=(HBRUSH)GetStockObject(WHILE_BRUSH); 
// What we wrote before, remember?
However, if the program calls the WINDOWS function invalidaterect to invalidate the rectangle in the customer area, the last parameter of the function specifies whether to erase the background. If this parameter is false (0), Windows will not erase the background, and the ferase field of the paintstruct structure will be true (non-zero) after beginpaint is called ).)

The rcpaint field of the paintstruct structure is a rect-type structure.

The rect structure defines the coordinates of the upper left corner and lower right corner of a rectangle.

Typedef struct _ rect {

Long left;

Long top;

Long right;

Long bottom;

} Rect, * prect;

Member left: Specifies the X coordinate in the upper left corner of the rectangle.

Top: Specifies the Y coordinate in the upper left corner of the rectangle.

Right: Specifies the X coordinate in the lower right corner of the rectangle.

Bottom: Specifies the Y coordinate in the lower right corner of the rectangle.

The rcpaint field of the paintstruct structure defines the boundary of the invalid rectangle ,. These values are in the units of pixels, and relative to the upper left corner of the display area. Invalid rectangle is the area to be repainted. The rcpaint rectangle in paintstruct is not only an invalid rectangle, but also a cropped rectangle. (A drawing can be restricted to a certain part of the customer area. This is called cropping. The cropping area can be a rectangle or a non-rectangle)

② For your understanding of the device description table, there are two other descriptions for your reference.

A device description table is a graphical structure that defines a set of graphical objects and their attributes and affects the output. Windows provides a device description table for interaction between applications and physical devices, which provides platform independence for application design. The device description table is also called the device context or the device environment.
A device description table is a data structure that contains information related to the drawing properties of a device (such as a display or printer. All painting operations are performed in the device description table. The device description table is different from the Win32 structure in most cases. applications cannot directly access the device description table and can only indirectly access the structure through the handle of the device description table by various related API functions.
The device description table is always related to a system hardware device. For example, the screen device description table is related to the display device, and the printer device description table is related to the printing device.
A device description table is generally called a device description table. It corresponds to a display device. On the Windows GDI interface, it is always related to a window or a display area in the window. In general, the device description table of the window generally refers to the customer area of the window, excluding the area occupied by the title bar and menu bar. For the whole window, the device description table is strictly called the window device description table, which contains all the display areas of the window. The two methods are the same, and the difference is that the operational range is different.
Once a Windows window is created, it automatically generates the corresponding device description table data structure. You can use this structure to perform the GDI operation on the display area of the window, such as dashes, text writing, drawing Bitmap, and filling. All these operations must be performed through the device description table handle.

B sun Xin: We can use an image metaphor to describe its role. Now there is an art teacher who asked his students to draw a Forest image. Some students use sketches, some students use watercolors, and some students use oil paintings, the pictures made by each student are forest, but their forms are different. If we want to draw a picture, the teacher specifies a painting method (for example, using a watercolor painting), we need to learn it before drawing the picture as required. If the plot (Tool) changes frequently, we need to spend a lot of time and energy learning and mastering it. Here, plotting is equivalent to graphics devices and drivers in computers. To create a graph, we need to master the graphics devices and drivers of the platform we use, and call the driver interface to display the image. The device drivers of different graphics devices are different. For programmers, it is too much work to master various drivers. Therefore, Windows provides us with a device description table, which enables us to change from a student role to a teacher role, as long as we can draw a forest by executing the following commands, the device description table deals with the device driver to complete the drawing. The effect of the image is determined by the graphic device used. For teachers, they only need to draw forest images. For programmers, as a teacher, they only need to get the handle of the device description table and use the handle to plot the table.

Note: Part of the content is quoted from Luo yunbin's 32-bit assembly language programming in Windows

Related Article

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.