All output in a program written for Windows must be done using a device context. A device context is an important part of the Windows Graphics Device Interface, or GDI. Device contexts are used by Windows and applications to provide device-independent output.
In this hour, you will learn
You also will build a sample program that demonstrates how a device context is used with text output.
New Term: A device context, often abbreviated as DC, is a structure that stores information needed when a program written for Windows must display output to a device. Device contexts are maintained by Windows. The device context stores information about the drawing surface and its capabilities. Before using any of the GDI output functions, you must create a device context.
Just a Minute: Deep down inside Windows, device contexts are actually structures that the GDI uses to track the current output state for a window. However, you never have access to the individual members of a device context; instead, all access to device contexts occurs through function calls.
The simplest reason to use device contexts is because they are required; there's simply no other way to perform output in a Windows program without them. However, using a device context is the first step toward using many of the GDI features that are available under Windows. Understanding how device contexts work can also help make your Windows programs more efficient.
New Term: Associating a GDI object with a device context is commonly referred to as selecting a GDI object into the device context.
A GDI object can be selected into a device context in order to provide specific drawing capabilities for the DC. Each GDI object can be used to create a different type of output. For example, a GDI pen object can be used to draw lines, whereas brush objects are used to fill screen areas. The GDI objects most commonly used with device contexts are listed in Table 11.1.
Object | Purpose |
Pen | Drawing lines |
Brush | Filling regions |
Bitmap | Displaying images |
Font | Typeface characteristics |
Windows and the MFC class library provide the following four different basic types of device contexts. Although you use these device contexts in different situations, the basic rules for their use are consistent.
With the exception of the information device contexts, each of the different DC types is used to create a different type of output. In addition, the MFC class library offers several different types of display device contexts, which are covered in the section "How to Use Device Contexts."
The goal behind using device contexts is to give programs written for Windows hardware independence. With a little care, your program can run on any display or printer that's supported by a Windows hardware driver. Most new output devices supply a driver if Windows doesn't currently provide automatic support. This means that programs you write today will work with display devices that have not been developed yet.
Just a Minute: Because of the way device contexts insulate a program written for Windows from the actual device hardware, output is often said to be "written to a device context." This independence from hardware makes it easy to send output to a printer that looks very much like screen output. You will learn more about printing in detail in Hour 21, "Printing."
In order to achieve true hardware independence, you must take a few precautions:
Device contexts can help by providing much of the information you need to stay hardware-independent.
When using Developer Studio, you almost always use an MFC class to gain access to a device context. The MFC class library offers not just one, but four different device context classes that can help make your life easier, at least when displaying output in a Windows program:
There are more MFC device context classes, but they are used for specialized purposes and are discussed elsewhere in this book. For example, the CPrinterDC class is discussed in Hour 21.
When you create a class using ClassWizard or AppWizard, often code that uses or creates a device context is provided automatically. For example, the OnDraw function for a typical view class is provided in Listing 11.1.
void CDisplayView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: add draw code here }
The device context used for the OnDraw function is created by the MFC framework before the OnDraw function is called. Because every OnDraw function must display some output, the device context is provided for you automatically, without the need for you to write any code.
Most functions that need a device context have one provided as a parameter, just like OnDraw. This is one of the ways MFC helps make your code easier to write and more reliable at the same time.
One of the most common mistakes made when using device contexts occurs when selecting a GDI object into a DC. When a device context is created, it contains a set of default GDI objects, as shown in Figure 11.1.
Figure 11.1.
A device context created with a collection of default GDI objects.
When a new GDI object--for example, a bitmap--is selected into a device context, the default GDI bitmap is passed as a return value to the caller. This return value must be saved so that it can be returned to the device context later. Listing 11.2 is an example of selecting a new bitmap into a DC and returning the previously selected GDI object at the end of the function.
CBitmap bmpHello; bmpHello.LoadBitmap( IDB_HELLO ); CBitmap* pbmpOld = dcMem.SelectObject( &bmpHello ); if( pbmpOld != NULL ) { // // Use the bitmap... // dcMem.SelectObject( pbmpOld ); }
Notice that the pbmpOld value is checked to make sure that it isn't NULL. If the call to SelectObject fails, the original bitmap is not returned. In that case, there's no need to return the original bitmap to the DC, because a new one was never selected.
CAUTION: You must restore the device context to its original state when you are finished with it. If you don't, resources that you have selected into a device context might not be properly released, causing your program to consume more and more GDI resources. This type of problem is known as a resource leak and is very difficult to track down--getting into the habit of always restoring the original object back into the device context is much better.
A group of commonly used GDI objects known as stock objects are maintained by Windows. These objects are much easier to use than objects that you create yourself. To select a stock object into a device context, use the SelectStockObject function:
HPEN hOldPen = pDC->SelectStockObject(BLACK_PEN);
Although stock objects do not need to be destroyed after they are used, attempting to destroy a stock object is not harmful. Table 11.2 describes the 16 stock objects available for use in your Windows programs.
Stock Object | Description |
BLACK_BRUSH | A black brush. |
DKGRAY_BRUSH | A dark gray brush. |
GRAY_BRUSH | A gray brush. |
HOLLOW_BRUSH | This is the same as NULL_BRUSH. |
LTGRAY_BRUSH | A light gray brush. |
NULL_BRUSH | A null brush, which is a brush that has no effect. |
WHITE_BRUSH | A white brush. |
BLACK_PEN | A black pen. |
NULL_PEN | A null pen, which is a pen that has no effect. |
WHITE_PEN | A white pen. |
ANSI_FIXED_FONT | A fixed-pitch system font. |
ANSI_VAR_FONT | A variable-pitch system font. |
DEVICE_DEFAULT_FONT | A device-dependent font. This stock object is available only on Windows NT. |
DEFAULT_GUI_FONT | The default font for user interface objects such as menus and dialog boxes. |
OEM_FIXED_FONT | The OEM dependent fixed-pitch font. |
SYSTEM_FONT | The system font. |
When a device context is created, it already has several stock objects selected. For example, the default pen is a stock object BLACK_PEN, and the default brush is the stock object NULL_BRUSH.
Time Saver: Stock objects can be used to restore a device context to its original state before the device context is deleted. Selecting a stock object into a device context will deselect a currently selected GDI object. This will prevent a memory leak when the device context is released:hBrNew = CreateSolidBrush(RGB(255,255,0)); SelectObject(hDC, hBrNew); // Original handle not stored . [Use the device context] . SelectObject(hDC, GetStockObject(BLACK_BRUSH));This technique is commonly used when it is not practical to store the handle to the original GDI object.
To demonstrate some basic ideas about how device contexts can be used, create a sample SDI program named DCTest. To help reduce the amount of typing required for GDI examples, the DCTest program will be used through Hour 14, "Icons and Cursors."
DCTest is an SDI program that displays some information about the current device context, its map mode, and information about the default font. It will be possible to change the view's map mode using a dialog box.
To begin building the DCTest example, create an SDI program named DCTest using MFC AppWizard. Feel free to experiment with options offered by AppWizard because none of the options will affect the sample project.
Using Figure 11.2 as a guide, create a dialog box that changes the map mode for the view display. Give the dialog box a resource ID of IDD_MAP_MODE.
Figure 11.2.
The IDD_MAP_MODE dialog box in the resource editor.
The dialog box contains one new control, a drop-down combo box with a resource ID of IDC_COMBO.
Using ClassWizard, add a class named CMapModeDlg to handle the IDD_MAP_MODE dialog box. Add a CString variable to the class as shown in Table 11.3.
Resource ID | Name | Category | Variable Type |
IDC_COMBO | m_szCombo | Value | CString |
That's the start of the DCTest project. It doesn't do much now, but you will add source code to the example as new device context topics are discussed for the remainder of this hour.
New Term: The mapping mode is the current coordinate system used by a device context.
In Windows, you use mapping modes to define the size and direction of units used in drawing functions. As a Windows programmer, several different coordinate systems are available to you. Mapping modes can use physical or logical dimensions, and they can start at the top, at the bottom, or at an arbitrary point on the screen.
A total of eight different mapping modes are available in Windows. You can retrieve the current mapping mode used by a device context using the GetMapMode function, and set a new mapping mode using SetMapMode. Here are the available mapping modes:
Modify the combo box in the IDD_MAPMODE dialog box so that it can be used to track the current mapping mode. You can set the contents of the combo box in the resource editor, just as you set other combo box attributes. Because this combo box contains a fixed list of items, adding them in the resource editor is easier than in OnInitDialog. Add the items from the following list to the combo box:
MM_ANISOTROPIC MM_HIENGLISH MM_HIMETRIC MM_ISOTROPIC MM_LOENGLISH MM_LOMETRIC MM_TEXT MM_TWIPS
Use the values from Table 11.4 to add a menu item and a message-handling function to the CDCTestView class. Unlike menu-handling functions you have seen earlier, the view class must handle this menu selection because the dialog box changes data that is interesting only for the view class.
Menu ID | Caption | Event | Function Name |
ID_VIEW_MAP_MODE | Map Mode... | COMMAND | OnViewMapMode |
Listing 11.3 contains the source code for the OnViewMapMode function, which handles the message sent when the new menu item is selected. If OK is clicked, the new map mode is calculated based on the value contained in the combo box. The view rectangle is invalidated, which causes the view to be redrawn.
void CDCTestView::OnViewMapMode() { CMapModeDlg dlg; if( dlg.DoModal() == IDOK ) { POSITION pos; pos = m_map.GetStartPosition(); while( pos != NULL ) { CString szMapMode; int nMapMode; m_map.GetNextAssoc( pos, nMapMode, szMapMode ); if( szMapMode == dlg.m_szCombo ) { m_nMapMode = nMapMode; break; } } InvalidateRect( NULL ); } }
Add an #include statement to the DCTestView.cpp file so the CDCTestView class can have access to the CMapModeDlg class declaration. Add the following line near the top of the DCTestView.cpp file, just after the other #include statements:
#include "MapModeDlg.h"
The CDC class has two member functions that are commonly used to collect information:
One common use for GetDeviceCaps is to determine the number of pixels per logical inch for the device associated with the DC. To retrieve the number of pixels per logical inch in the horizontal direction (also known as the x-axis), call GetDeviceCaps and pass an index value of LOGPIXELSX as a parameter:
int cxLog = pDC->GetDeviceCaps( LOGPIXELSX );
Later this hour you will use GetDeviceCaps to display this information in the DCTest example.
Just a Minute: GetDeviceCaps is used primarily when printing; you can use this function to determine whether the printer supports specific GDI functions. In Hour 21 you will see how GetDeviceCaps is used to determine whether a printer can have bitmaps transferred to it.
GetTextMetrics is used to fill a TEXTMETRIC structure with a variety of information:
TEXTMETRIC tm; pDC->GetTextMetrics(&tm);
The TEXTMETRIC structure has a large number of member variables that contain information about the currently selected font. The most commonly used members of the TEXTMETRIC structure are shown in Table 11.5.
Member | Specifies... |
tmAscent | The number of units above the baseline used by characters in the current font. |
TmDescent | The number of units below the baseline used by characters in the current font. |
TmHeight | The total height for characters in the current font. This value is equal to adding the tmAscent and tmDescent values together. |
TmInternalLeading | The area reserved for accent marks and similar marks associated with the font. This area is inside the tmAscent area. |
TmExternalLeading | The area reserved for spacing between lines of text. This area is outside the tmAscent area. |
TmAveCharWidth | The average width for non-bold, non-italic characters in the currently selected font. |
TmMaxCharWidth | The width of the widest character in the currently selected font. |
To get the height of the currently selected font, call the GetTextMetrics function and use the value stored in the tmHeight member variable:
TEXTMETRIC tm; pDC->GetTextMetrics(&tm); nFontHeight = tm.tmHeight;
In order to display information about the current map mode, you must first create a collection based on CMap, one of the template collection classes. The CMap variable, m_map, associates an integer map-mode value with a CString object that describes the map mode. As shown in Listing 11.4, add two new variables to the CDCTestView class declaration in the attributes section.
// Attributes private: CMap< int, int, CString, CString > m_map; int m_nMapMode;
When using one of the MFC collection classes in a project, you should always add an #include "afxtempl.h" statement to the stdafx.h file in the project directory. This include directive adds the MFC template declarations to the project's precompiled header, reducing project build time.
#include "afxtempl.h"
The source code for CDCTestView::OnDraw is provided in Listing 11.5. The current map mode is displayed, along with text and device metrics. The text metrics vary depending on the current logical mapping mode, while the device measurements remain constant. Some of the mapping modes will display the information from top to bottom, whereas some of the modes cause the information to be displayed from bottom to top.
void CDCTestView::OnDraw(CDC* pDC) { // Set mapping mode pDC->SetMapMode( m_nMapMode ); // Get client rect, and convert to logical coordinates CRect rcClient; GetClientRect( rcClient ); pDC->DPtoLP( rcClient ); int x = 0; int y = rcClient.bottom/2; CString szOut; m_map.Lookup( m_nMapMode, szOut ); pDC->TextOut( x, y, szOut ); // Determine the inter-line vertical spacing TEXTMETRIC tm; pDC->GetTextMetrics( &tm ); int nCyInterval = tm.tmHeight + tm.tmExternalLeading; y += nCyInterval; szOut.Format( "Character height - %d units", tm.tmHeight ); pDC->TextOut( x, y, szOut ); y += nCyInterval; szOut.Format( "Average width - %d units", tm.tmAveCharWidth ); pDC->TextOut( x, y, szOut ); y += nCyInterval; szOut.Format( "Descent space - %d units", tm.tmDescent ); pDC->TextOut( x, y, szOut ); y += nCyInterval; szOut.Format( "Ascent space - %d units", tm.tmAscent ); pDC->TextOut( x, y, szOut ); int cxLog = pDC->GetDeviceCaps( LOGPIXELSX ); y += nCyInterval; szOut.Format( "%d pixels per logical horiz. inch", cxLog ); pDC->TextOut( x, y, szOut ); int cyLog = pDC->GetDeviceCaps( LOGPIXELSY ); y += nCyInterval; szOut.Format( "%d pixels per logical vert. inch", cyLog ); pDC->TextOut( x, y, szOut ); }
Compile and run the DCTest example. Figure 11.3 shows the DCTest main window, with device measurements and text metrics displayed.
Figure 11.3.
Running the DCTest example.
As a final topic in this hour, it's important to understand how colors are represented in Windows applications. Color values are stored in COLORREF variables, which are 32-bit variables defined as
typedef DWORD COLORREF;
Each COLORREF is a 32-bit variable, but only 24 bits are actually used, with 8 bits reserved. The 24 bits are divided into three 8-bit chunks that represent the red, green, and blue components of each color.
A COLORREF is created using the RGB macro, which stands for Red, Green, and Blue--the three colors used for color output in a Windows program. The RGB macro takes three parameters, each ranging from 0 to 255, with 255 signifying that the maximum amount of that color should be included in the COLORREF. For example, to create a COLORREF with a white value, the definition would look like this:
COLORREF clrWhite = RGB(255,255,255);
For black, the definition would look like this:
COLORREF clrBlack = RGB(0,0,0);
You can change the current text color used for a device context through the SetTextColor function. SetTextColor returns the previous text color used by the device context.
Listing 11.6 shows two different ways in which you can use the SetTextColor function. The first method uses the RGB macro inside the SetTextColor function call; the next method creates a COLORREF value that is passed as a parameter.
// Change text color to pure green COLORREF colorOld = pDC->SetTextColor(RGB(0,255,0)); // Change text color to pure blue COLORREF colorBlue = RGB(0,0,255); pDC->SetTextColor(colorBlue); // Restore original text color pDC->SetTextColor(colorOld);
In this hour you learned about the Graphics Device Interface, or GDI. You also learned the basics of the device context, as well as some of the MFC classes that are used to manage them. You built a sample program that enables you to change and display information about an output device and its map mode.
The Workshop is designed to help you anticipate possible questions, review what you've learned, and begin thinking ahead to putting your knowledge into practice. The answers to the quiz are in Appendix B, "Quiz Answers."
© Copyright, Macmillan Computer Publishing. All rights reserved.