"VC ++ Technical Insider" (Fourth Edition) Reading Notes

zhaozj2021-02-16  90

"VC Technical Insider" (Fourth Edition) Reading Notes

Keywords: VC original author Name: loose_went article original: vczx.com --http://www.vczx.com/minute.php

Written in front:

The "VC Technical Insider" version of the webmaster is - Pan Aimin and Wang Guosheng, the fourth edition published by Qinghua University, because sometimes it is busy, can not be updated in time, please forgive me!

On the first day of Windows programming mode The second day MFC application framework Third Day message mapping and view class fourth day resource and compile the fifth day basic event processing Six Day mapping mode seventh day roll window eighth day Ninth day GDI object tenth day Windows color map

First day Windows programming mode

There must be a WinMain function in the Windows program because the most important task of this function is to create the main window of the application. The maximum difference between the Windows program and the MS-DOS program is that the MS-DOS program is to obtain the user input by calling the functionality of the operating system, and the Windows program is a message sent by the operating system to handle the user input. Windows messages are strictly defined and apply to all programs. Windows offers a universal graphics device interface (GUI), we don't have to pay an equipment environment by calling (GDI) functions and hardware, Windows automatically maps the device environment structure to the appropriate physical device. The data required in the Windows programming is stored in the resource file, so that the connector can combine compiled binary code and binary resource files to generate executables. Resource files can include bitmaps, icons, menu definitions, dialog design, and even formats that the user's own definition can be included. The Windows program allows dynamic connection target modules, and multiple applications can share the same dynamic connection library. The VC source program browser enables us to understand or edit the program from the perspective of class or functions, not directly from the file. If you can skilled the source code browser when you see someone else's source code. The main viewing status of the source program browser has the following: Definitions and References - Select any function, variable, type, macro definition to see it in the project, and where and where it is used. Call graph / caller graph - For the selected function, give it an illustration of its call to the called function. Derived Class Graph / Base Class Graph - a graphical representation of the classic relationship, you can see the derived class and base class of the selected class, and members. FILE OUTLINE - For selected files, list classes, functions, and data members in the file, and also display the location and use positions defined. It can be seen that Source Brower is much more useful than the Class View. For this chapter, LOOSE_WENT is recommended to generate an empty program in VC 6, then try to see which files are, and their class level, function, macro, structure definition, I just do this, Learning is not working.

Top of page

Second Day MFC Application Framework

• The MFC is a C Microsoft Windows API® MFC generated application uses a standardized structure. • The application generated by the MFC is short and running fast. • The VC tool reduces the complexity of the encoding, which is of course, many code is handled by it, huh, huh. • The function of the MFC library application framework is very rich. The above is the advantage of the MFC library. Although MFC has such an advantage, I personally think that I can't learn it, I want to learn, then you must master C , which is unquestionable. Maybe just start, you feel that the harvest is very interesting, but it is very interesting, but it is necessary to further improve, no C foundation is difficult. So the webmaster recommends that there is a good time when you study, so you can learn! The application framework is a class library superchard. Let's first look at an example and see how powerful MFC! You only need to add a line of code, or even a line does not need to add a few mouse to create a Windows program, do not believe, try: 1. Open the VC 6 From the menu, select New, name "MyApp". 2. Select the MFC AppWizard [EXE] option, except STEP 1 to select other STEP defaults outside the single text file. 3, in the Class View Select the onDraw () member function of the CMYAppView class, you can see the following on the C compiler to see the following Void CMYAppView :: OnDraw (CDC * PDC) {CMYAppdoc * PDOC = getDocument (); assert_valid (pdoc); // TODO: add draw code for native data here} in // TODO: location add draw code for native data here a line of code is increased void CMyAppView :: OnDraw (CDC * pDC) {CMyAppDoc * pDoc = GetDocument (); ASSERT_VALID (pDoc) PDC-> Textout (10, 10, "May VC can become a good friend of VC online!"); // Increased row // Todo: add draw code for native data here} is over, it is so simple. Compile operation. see it? This program has all features of Windows programs, such as menus, toolbar, status bar, maximizing, off, and even about dialogs, print preview ..... All, this is a dynamically created by MFC through MFC application. From this small example, you can see how conveniently designed the Windows program with VC / MFC.

Let's take a look at the examples in your book to further understand the application framework. 1. Build a Win32 Application application. 2. Select Project-> Add to Project-> Files, create a file called myapp.h and a name myapp .cpp. 3, add code: (It is best to take a down code to the compiler, don't use Ctrl C / Ctrl V) // ******************** ************************ // myapp.h //

Class CMYAPP: PUBLIC CWINAPPPPPPPPPPPPPPP: Virtual Bool InitInstance ();

class CMyFrame: public CFrameWnd {public: CMyFrame (); protected: afx_msg void OnLButtonDown (UINT nFlags, CPoint point); afx_msg void OnPaint (); DECLARE_MESSAGE_MAP ()}; // ************ ************************************************* // myapp.cpp //

#include "afxwin.h" #include "myapp.h" CMyApp theApp; // create a CMyAPP objects BOOL CMyApp :: InitInstance () {m_pMainWnd = new CMyFrame (); m_pMainWnd-> ShowWindow (m_nCmdShow); m_pMainWnd-> UpdateWindow (); Return True;

Begin_MESSAGE_MAP (CMYFRAME, CFRAMEWND) ON_WM_LBUTTONDOWN () ON_WM_PAINT () end_MESSAGE_MAP ()

CMYFRAME :: CMYFRAME () {Create (Null, "MyApp Application");} Void CMYFRAME :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {Trace ("Entering CMYFrame :: ONLBUTTONDOWN -% LX,% D,% D / N "(long) nflags, point.x, point.y);

Void cmyframe :: onpaint () {cpaintdc dc (this); dc.textout (0,0, "hello world!");}

4, compile operation, error. why? It hasn't added MFC support, in the Project Setting Options General Properties page Select "Use MFC in A Static Library" 5, press Ctrl F5, how, simple? Let's take a look at some elements in this program. 1WinMain function: Windows always requires every application to have a Winmain function, you can't see because it is hidden within the application framework. 2CMYAPP class: The object of the CMYAPP class represents an application, and the CWINAPP base class determines most of its lines. 3 Startup startup: Windows calls the Winmain function when running the application, and WinMain will find the global object theApp for the application. 4CMYAPP :: InitInstance member function: Discover theApp automatically calls the overloaded virtual function initInstance to complete the constructive and display of the main window. 5cwinapp :: Run Member Function: WinMain followed the RUN function after calling InITInstance, which is hidden in the base class to pass the message to the display window. 6CMYFRAME class: This type of object represents the main window of the application. Its constructor calls the CREATE function of the base class CFrameWnd creates a specific window structure. 7CMYFRAME :: ONLBUTTONDOWN function: Demonstration message processing mechanism, when the mouse buffer is pressed to the CMYFrame's ONLBUTTONDOWN function, if you select F5 to compile the run, you can see the TRACE macro display in the debug window. Information Entering CMYFRAME :: ONLBUTTONDOWN - 1,309,119entering CMYFRAME :: Onlbuttondown - 1,408,2218cmyframe :: onpaint function: Applications You need to call this function, will display "Hello World!" Is here because each window is When changing, "Hello World!" Is shown, you can try to speak statements: cpaintdc dc (this); dc.textout (0,0, "hello world!"); Writing, for example, writing in Void CMYFRAME :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {Trace ("Entering CMYFRAME :: ONLBUTTONDOWN -% LX,% D,% D / N", (long) NFLAGS, POINT.X, POINT.Y); CPAINTDC DC (THIS ); DC.Textout (0, 0, "Hello World!");} After the operation, "Hello World!" is displayed when you click the left button, but when the window minimizes, "Hello World!" is not seen. 8 Turn off the application: There will be a series of events when the user shuts down the application. First, the CMYFRAME object is deleted, then exits RUN, and then exits WinMain, and finally remove the CMYAPP object. Through the above example we see that most of the program is included in the base class cwinapp and cframewnd, we only write very little functions, you can complete a complicated feature. So the application framework is more than just a class library, but also defines the structure of the application. In addition to the base class, the WinMain function is included, and the message processing, diagnostics, DLLs, etc. are included in the application framework. Top of page

Third Day Message Mapping and View Class

The MFC library applicator framework does not use virtual functions to process Windows messages, but through macros to map messages to the corresponding members of the derived class. Documentation - The view structure is the core of the application framework. It separates the data from the user to the observation of the data, so the biggest advantage is that the same data can correspond to multiple views. For example, with an stock quotation data, there can be both report observation windows, or there can be a graphic viewing window. The view is a normal window, which is an object of a class derived from the CView class from the MFC library. The view class is divided into two source file modules: header file (h) and source code file (CPP). Create an SDI application with AppWizard, which has the following file (assuming the project name EXC01): EXC01.DSP project file, Visual Studio uses it to create an application EXC01.DSW workspace file, including an item EXC01.DSPEXC01.RC ASCII Code Resource Description Files EXC01View.cpp Contains CEXC01View class member function and view class file EXC01VIEW.H Contains CEXC01View class definition view class header file EXC01.OPT binary, telling developer Studio which files are open, how to sort Readme.txt Text files for all files generated resource.h contains header files that #define constant definitions It can be seen from the code of EXC01VIEW.CPP and EXC01VIEW.H. These two files have completely defined CEXC01VIEW. Class, and this class is the core of this application. The object of the CEXC01VIEW class is associated with the application's window. All "Actions" of the application will be displayed in this window. The two most important base classes of the CEXC01VIEW class are CWND and CView classes. The CWnd class provides the CEXC01VIEW window properties, while the CView class provides contacts between it and other parts of the application framework, especially between the document, and the link window. This must be remembered. Let's take a look at how to draw in the window. The most important function is an onDraw () function, it is a virtual function, each window is swaled, the application must call this function first. Note: Although the window can be drawn at any time, it is best to have a certain degree of change to a certain extent, then taught the onDraw () function, which is high. In the MFC, the device environment is represented by the C CDC class object, which is transmitted to the onDraw () function as a parameter so that we can call many member functions of the CDC to complete a variety of drawings. Find the onDraw () function, replace the function with the following statement: PDC-> Textout (0, 0, "Hello World!"); PDC-> Ellipse (CRECT (0, 20, 100, 12)); Re-compilation, see what? TEXTOUT and ELLIPSE are members of the device environment CDC, and the MFC library provides a class CRECT used to represent the Windows rectangle, which is passed as a parameter to the Ellipse function as a parameter, when the external rectangle is wide and high When equally, the Ellipse function draws a circle. Top of page

Day 4 Resources and Compilation

The resource file (that is, the application name and extension is .RC) to largely determine the user interface of the application. The resource files in the VC include the following: Accelerator // Simulation menu and toolbar selection keyboard definition Dialog // icon's layout and content ICON // icon There are two types of 16x16 32x32. Menu // Applications' main menu and the pop-up menu String Table // Some strings are not belong to the C source code section Toolbar // Toolbar. Version // Program Description, version number, support language information. In addition to the above information, the .rc file also includes the following statement: #include "afxres.h" #include "afxres.rc" their role is to include some universal MFC library resources suitable for all applications, including strings , Graphics buttons, and some elements you need to print. There is not much to say about the use of the resource editor, because its operation is simple, you need to pay attention to the resource.h is an ASCII code file to edit with a text editor, but if you use the text editor, The changes made when using the resource editor next time may be lost, so we should try to edit the resources of the application in the resource editor, and the new resource content back automatically adds in our program, such as Resource .h without we are worried. Compiling in VC has two modes, one is Release Build another is Debug Build. The difference between them is that Release Build does not debug the source code. Does not consider the MFC diagnostic macro, use the MFC Release library, compile ten pairs of applications, and Debug Build is just the opposite, it allows for sources The code is debugged, which can define and use the MFC diagnostic macro, which uses the MFC Debug library, which is not optimized. So we should develop applications in Debug mode, then publish applications in Release mode. There will be a debug folder and a Release folder in our project folder, store the output file and intermediate files. Diagnostic macro is a favorable tool for the detection program status when we compiler, such as the TRACE macro used, you can get the diagnostic information you need at the Debug window, without setting the dialog, the method will be released. Automatically filter out this information. For better management projects, it is best to understand how the system handles the pre-translated header file. VC has two precompiled systems: automatic and manual. This part of the author said not much, it is recommended that the reader will take a look. Top of page

Day 5 Basic Event Treatment

Operation of the user in the window will cause Windows to automatically send a message to the window. We explain in an example: For example, we press the left mouse button in the window, Windows will send an ON_LBUTTONDOWN message to the window, then in the window class, you must include the following member functions: void cmyview :: ONLButtondown (uint nflags, cpoint Point) {// Event Processing Code Here} Also in the class header file also contains the corresponding function declaration: AFX_MSG Void OnlButtondown (uint nflags, cpoint point) There is also a message mapping macro in the code file to use the ONLBUTTONDOWN function. and application framework together: BEGIN_MESSAGE_MAP (CmyView, CView) ON_WM_LBUTTONDOWN () // other message map entriesEND_MESSAGE_MAP Finally, include the following statement in the library header file: DECLARE_MESSAGE_MAP () these steps, we can be done by means of ClassWizard . This is the process of message mapping. The MFC library provides a message control function for 140 Windows messages, and we can also define your own messages. The five messages listed below are special attention to it (more detailed in MSDN). WM_CREATE This message is the first message for Windows sent to the view. This message will be sent when the application framework calls the create function. At this point the window has not created completed, which is not visible, so the Windows functions that depend on the fully activated state cannot be invoked within the message control function onCreate. If you need to call within the overnitialUpdate function in the overloaded OnInitialUpdate function. However, note that the ONInitialUpdate function in the SDI application may be called multiple times. WM_CLOSE When the user turns off the window, the system will send a WM_CLOSE message. If the derived class redefines the onClose function, you can fully control the shutdown process, you can release the work such as reminding the user store to complete. We can reach the same purpose by overloading the cDocument :: savemodified virtual function. WM_QUERYENDSESSION can be seen from the literal meaning that when the user exits Windows, or when the exitWindows function is called. Windows will send a WM_QueryEndSession message to all the running applications, processed by the ONQUERYENDSESSION message mapping function. It should be a WM_ENDSESSION message after it. After Windows sends a WM_CLOSE message, WM_DESTROY is then sent to the WM_DESTROY message, although the window has already closed but actually not completely cleared, you can see the application process in the task manager (I think a lot of Trojans or viruses are windows Programs, their approach is to generate a window that has been active but does not display it), using this message control function to clear work on something that exists in the current window, but must pay attention to the ONDESTROY of the base class Functions, not terminating the destructor of the window in the Ondestroy function of the user's own view, and the termination sector should be in the onClose function. WM_NCDESTROY is this message when the last message sent by the window is canceled. We can do some of the last processing work that does not depend on whether the window is active in the onNCDESTROY function, (I really can't think of what else do you need? The friend can give an example), pay attention to call the base class. ONNCDESTROY function.

The name of non-static data members in the MFC library is prefixed by m_. One window has a rectangular "customer area", the getClient member function in CWnd can give the size of the customer area, only to draw in the customer area. The standard Windows application will first register a window class, which is different from the C class, and during the process, you also need to specify a window process for each class. Each time the application calls CREATEWINDOW to create a window, you must specify a window class as a parameter, which connects the newly established window and window procedure function. When Windows sends a message to the window, this function will be Call to check the message code that is passed with parameters. Top of page

Sixth day mapping mode

The so-called mapping mode is that it is the coordinate system. By default, the image unit drawn image unit is pixel because the device environment uses the default mapping mode MM_Text, so the graphics drawn by the following statement is the square of the length of 200 pixels: PDC-> Rectangle (CRECT) 0,0,200,200)); then, do we want to draw a length and wide? What should I do? This must change the default mapping mode of the device environment to mm_himetric, and its image unit is 1 / 100mm instead of pixels. Its Y-axis direction and the opposite of mm_text, it is down, so it can be drawn 4 × 4cm square with the following statement: PDC-> setmapmode (mm_himetric); PDC-> Rectangle (CRECT (0, 0,4000, -4000)); Let's take a look at how Windows provides mapping mode. 1, mm_text mapping mode This mode, the plot unit is pixel, X axis right increment, Y axial down, we can use the CDC's setViewportorg and setwindoworg function to change the position of the coordinate original, the following code is to put the coordinate original Set in (100, 100), draw a 200 × 200 pixel square, at which point the logical coordinate point (100, 100) is mapped to the device coordinate point (0, 0), the next scrolling window is used Transform. Void CMYVIEW :: OnDraw (CDC * PDC) {PDC-> setmapmode (mm_text); PDC-> SetWindoworg (CPOINT (100, 100)); PDC-> Rectangle (CRECT (100, 100, 200, 200));} 2, fixed scale mapping mode Windows Provided A set of very important fixed-scale film and television patterns, all of this model follows the X axis right decrement, and the y-axis decrement rules, and we can't change it. The only difference between the fixed ratio mode is the actual scale factor. The following table lists the corresponding cases of film and television mode and proportional factors:

Mapping mode logic unit mm_loenglish 0.01 inches mm_hienglish 0.001 inch mm_lometric 0.1mm mm_himetric 0.01mm mm_twips 1/1440 inches

MM_TWIPS mode is often used for printers. 3, the variable scale mapping mode Windows also provides two mapping mode MM_ISOTROPIC and MM_ANISOTROPIC, which allow us to modify the proportional factor and coordinate original. In MM_ISOTROPIC mode, the aspect ratio is always 1: 1, just like changing the image when the image is changed, while the mm_anisotropic mode can independently change the proportional factor of X and Y, that is, the circle can become a flat circle. The above is a common mapping mode. The author suggests: We don't have to die in these models, just use it when you use it, even if you blame MSDN, this stuff is really good! After setting the mapping mode and the corresponding parameters, we can convert the logical coordinates to the device coordinates with the DPTOLP function to convert the device coordinates into logical coordinates. So what kind of coordinates we use? There are some rules as follows: 1 Can think that all member functions of the CDC use logical coordinates to parameter 2 can think that all member functions of CWnd use the device coordinates as parameters 3 All selected tests should be used to use device coordinates, and the definition of the area should be used. Some functions like CRECT:: PtinRect can only have the correct result of the device coordinates 4 to save some long-term use of the logical coordinates, if the device coordinate, then only the user rolls, coordinate Under normal circumstances, we set the mapping mode in the virtual function onprepAREDC of CVIEW, and the application framework calls this virtual function before calling the onDraw function. Top of page

Scroll windows on the seventh day

The CView class does not directly support the window scrolling. To implement the window scrolling, use the CVIEW's derived class CScrollView class. The member function of the CScrollView can handle the scroll bar and send the view WM_HScroll message to implement the scroll of the window. In the document-view structure, the view window is built, the framework first calls the OnInitialUpdate virtual function, and then call the OnInitialUpdate function before the framework first calls the onDraw function, so the initialization of the scrolling window is set to the InInitialUpdate function. Let's create a scrolling sample program A: 1. Create a document with AppWizard - Note that the base class of the Caview should be CScrollView instead of CVIEW at step six steps. 2. Add data members M_Rectellipse and M_ncolor in Caview. 3, modify the OnInitialUpdate function as follows: void caview :: oninitialupdate () {cscrollview :: oninitialupdate (); csize sizetotal (20000, 30000); // Logic window size 20 × 30cmcsize sizepage (sizeetotal.cx/2, sizetotal.cy/ 2); CSIZE Sizeline (sizel.cx/50, sizetotal.cy/50); setscrollsizes (mm_himetric, sizeetotal, sizepage, size)

4}, OnKeyDown function generating control messages with the ClassWizard WM_KEYDOW, and edit the code as follows: void CAView :: OnKeyDown (UINT nChar, UINT nRepCnt, UINT nFlags) {// TODO: Add your message handler code here and / or call default

Switch (cchar) {copy vk_home: ONVScroll (SB_TOP, 0, NULL); OnHScroll (SB_LEFT, 0, NULL); Break; Case VK_END: ​​ONVScroll (SB_BOTTOM, 0, NULL); OnHScroll (SB_Right, 0, Null); Break; ; case VK_UP: OnVScroll (SB_LINEUP, 0, NULL); break; case VK_DOWN: OnVScroll (SB_LINEDOWN, 0, NULL); break; case VK_PRIOR: OnVScroll (SB_PAGEUP, 0, NULL); break; case VK_NEXT: OnVScroll (SB_PAGEDOWN, 0, NULL); Break; Case VK_LEFT: OnHScroll (SB_LINELEFT, 0, NULL); Break; Case VK_Right (SB_Lineright, 0, Null); Break; Default: Break;}} 5, editing constructor and the onDraw function are as follows: CAVIEW :: Caview (): m_rectellipse (0, 0, 4000, -4000) {// Todo: add construction code herem_ncolor = gray_brush;} ... Void Caview :: Ondraw (CDC * PDC) {PDC-> SelectStockObject (m_ncolor); pDC-> Ellipse (m_rectEllipse);} 6, and edit the message mapping WM_LBUTTONDOWN message handler OnLButtonDown follows: void CAView :: OnLButtonDown (UINT nFlags, CPoint point) {// TODO: Add your message handler code here and / or call default

CClientDC dc (this); OnPrepareDC (& dc); CRect rectDevice = m_rectEllipse; dc.LPtoDP (rectDevice); if (rectDevice.PtInRect (point)) {if (m_nColor = GRAY_BRUSH) m_nColor = WHITE_BRUSH; elsem_nColor = GRAY_BRUSH;} InvalidateRect ( Recipdevice);} Compile and run the look. In addition, we must pay special attention to the following five more special Windows messages: 1. WM_CREATE message This message is the first message sent to the view. This message will be sent because the application framework calls the create function. The window creation is not completed, so the Windows function that depends on the window is in a fully activated state cannot be called in the Create function. However, for the SDI application, the OnInitialUpdate function can be called multiple times during view survival. 2, WM_Close Message When the user turns off the window from the system menu or the parent window is turned off, Windows sends a WM_CLOSE message. 3, WM_QUERYENDSESSION message When the user exits Windows, Windows sends a WM_QueryEndSession message to the running program, handling the message's mapping function is ONQUERYENDSession. 4, WM_DESTROY message Windows After sending the WM_CLOSE message, then send a WM_DESTROY message, the message mapping function is ONDESTROY. When the program receives the message, it will assume that the window has disappeared, but is still active. With this message control function, you can clean up all things dependent on the current window, but you must remember that you should use the base class onDestroy instead of the "Termination" window in the onDestroy in your own view. The processing of the termination sector should be in the onClose function. 5, WM_NCDESTROY message When the last message sent when the window is canceled is this message, because all the windows are turned off, so we can do some last processing that does not depend on whether the window is active in the onNCDESTROY function. But be sure to call the ONNCDESTROY function of the base class. Do not cancel a dynamic application window object in OnNCDestroy, this work is done by a special virtual function PostncDestroy's special virtual function PostncDestroy, which is called by the base class onncdestroy. When to cancel the window object is the most appropriate, go to the MFC's online documentation! Top of page

Day 8 Equipment Environment

Any program needs to call the Graphics Device Interface (GDI) function during the drawing, and the GDI contains some functions of drawing points, lines, rectangles, ellipses, bitmaps, and text. Windows's device environment is a key element of GDI. It represents physical devices, each C device environment object has a corresponding Windows device environment, and is identified by a 32-bit HDC handle.

The base class CDC in the MFC contains all the member functions required by the drawing, and all derived classes are only different from the constructor and the destructor. For the monitor, commonly used derived classes have CClientDC and CWindowDC.

Displays the device environment class CclientDC and CWindowDC, CclientDC class drawings are only limited to the customer area, that is, the border, menu bar, and title bar, and the CWindowDC class can. Simply, if you create a CClientDC object, point (0,0) refers to the upper left corner of the customer area. If the CWindowDC object is created, the point (0,0) refers to the top left corner of the entire screen. When creating a CDC object, don't forget to delete it when you are right, otherwise the program will be lost before exiting. To ensure that the equipment environment object can be deleted in a timely manner, there are two ways:

One is to construct the object in the stack, such as in the ONLBUTTONDOWN function, which is automatically called when the function returns.

Void CMYVIEW :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {

CRECT RECT;

CClientDC DC (this); // Construction DC on The Stack

...

} // DC Automatic or Destroyed

The other is to obtain the device environment pointer by calling the member function GETDC of the CWnd, but at this time, RLLEASEDC must be called to release the device environment.

Void CMYVIEW :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {

CRECT RECT;

CDC * PDC = Getdc ();

PDC-> getClipbox (Rect);

ReleaseDC (PDC); // Don't forget this sentence

}

Note: Don't delete the CDC object that is passed to the onDraw function as a parameter, and the application framework automatically controls its deletion.

When drawing, we can ink the device environment, then we have to rely on the current state of the device environment while drawing, including:

? The selected GDI drawing object, such as pen, brush and font, etc.

? Mapping mode for scaling when drawing

Other details, such as the alignment of the text, polygonal fill status

When you create a device environment object, you usually have some default features, and other features are set by the member function of the CDC class, which can select the GDI object into the device environment by overloading the SelectObject function.

If we want to write the onpaint function, you need to use the CPAINTDC class. This class is more special. Its constructor and the work completed by the designer function are for display. Once we get a CDC pointer, you can Use it as any device environment pointer.

Top of page

Ninth day GDI object

All GDI objects are derived from abstract base class cgdiobject. Below is a list of GDI derived classes:

The CBitMap-bitmap is a bit matrix. Each display pixel corresponds to one or more bits. We can use the bitmap to represent an image, or it can be used to create a brush.

The CBRUSH - The brush defines a pixel in the form of bitmaps that use it to fill the colors in the area.

CFont - font is a collection of all characters with a certain style and size.

The CPALETTE - the palette is a color map interface.

CPEN - pen is a tool for line and a shape, which can specify the width of the drawing, and draw a dotted line, solid line, etc.

The CRGN - the area is a range that can be tested with it to fill, crop, and mouse points.

We only need to construct a derived class object for the CGDiobject class without constructing it, some GDI derived classes allow constructors to complete the task of creating objects by step, such as CPEN and CBRUSH. Some derived objects should be two steps, such as CFont and CRGN, first call the default constructor, then call the corresponding creation functions, such as CREATEFONT, CREATEPOLYGONRGN, etc. The CGDiobject class has a false patterned function. If a target of its derived class is constructed, delete it before the program exits, in order to delete it, you must first separate it from the device environment. So how do you separate? In fact, the SelectObject member function of the CDC class selects the GDI object to the device environment, it has been separated from the device environment, but before the new object is not selected, the old object cannot be separated. So when you choose your own GDI object, save the original GDI object, after the task is completed, then it will restore it, so you can separate your GDI object and delete it. Let's take a look at one example:

Void CMYVIEW :: OnDRAW (CDC * PDC) {

CPEN NewPen (ps_dashdotdot, 2, (colorref) 0); // Black 2 Pixels Wide

CPEN * POLDPEN = PDC-> SelectObject (& NewPen);

PDC-> Moveto (10, 10);

PDC-> LineTo (110, 10);

PDC-> SelectObject (Poldpen); // newpen is separated

} // newpen automatically deletes when the function exits

For some stock GDI objects, because they are part of the Windows system, I don't have to delete them. The MFC library function SelectStockObject can select an inventory object into the device environment and return to the pointer to the originally selected object, while the object is separated. In the above example, we can use the stock object instead of "old" object:

Void CMYVIEW :: OnDRAW (CDC * PDC) {

CPEN NewPen (ps_dashdotdot, 2, (colorref) 0); // Black 2 Pixels Wide

PDC-> Moveto (10, 10);

PDC-> LineTo (110, 10);

PDC-> SelectStockObject (Black_pen); // Newpen is separated

} // newpen automatically deletes when the function exits

For display device environments, at the entrance to each message control function, the device environment is not initialized, so each time you must set the device environment from the beginning, due to the temporaryness of the GDI object pointer returned by SelectObject, The program framework deletes the C temporary object pointer when the function returns, so it is not possible to save the device environment pointer in the class's data member, and to convert it to the Windows handle with the GetSafeHandle member function (the only GDI that can last for a long time ID).

Note that when deleting objects pointed by selectObject, be careful, if the object is our own application, you can delete, if it is temporary, you can't be removed casually.

Top of page

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

New Post(0)