Teach Yourself Visual C++® 5 in 24 Hours

Previous chapterNext chapterContents


- Hour 11 -
Device Contexts

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.

What Are Device Contexts?

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.

Types of GDI Objects

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.

Table 11.1. Commonly used GDI objects in Windows programs.

Object Purpose
Pen Drawing lines
Brush Filling regions
Bitmap Displaying images
Font Typeface characteristics

Types of Device Contexts

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."

Hardware Independence

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.

How to Use Device Contexts

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.

Wizard Support for Device Contexts

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.

TYPE: Listing 11.1. A typical OnDraw function.

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.

Selecting a GDI Object

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.

TYPE: Listing 11.2. Selecting and restoring a GDI object.

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.

Stock Objects

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.

Table 11.2. Windows stock objects.

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.


DCTest: A Device Context Example

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.

Creating the Mapping Mode Dialog Box

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.

Table 11.3. New CString member variable for the CMapModeDlg class.

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.

Setting Mapping Modes

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:

Modifying the Mapping Mode Dialog Box

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

Adding a Menu Item

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.

Table 11.4. New member functions for the CDCTestView 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.

TYPE: Listing 11.3. The CDCTestView::OnViewMapMode function.

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"

Collecting Information from a Device Context

The CDC class has two member functions that are commonly used to collect information:

Using the GetDeviceCaps Function

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.

Using the GetTextMetrics Function

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.

Table 11.5. Common member variables of the TEXTMETRIC structure.

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;

Modifying the CDCTestView Class

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.

TYPE: Listing 11.4. New member variables added to the CDCTestView class declaration.

// 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.

TYPE: Listing 11.5. The CDCTestView::OnDraw function.

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.

Using Color in Windows Applications

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.

TYPE: Listing 11.6. Changing the text color using the SetTextColor function.

// 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);

Summary

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.

Q&A

Q I'm having trouble drawing an ellipse that is exactly six inches across. I used GetDeviceCaps to retrieve the LOGPIXELSX and LOGPIXELSY values, but the image is drawn either too small or too large. How can I draw an image to an exact physical size?

A The LOGPIXELSX and LOGPIXELSY values are supplied by the video driver. These values are approximate, and are really just a wild guess. There's no way to determine the true number of pixels per inch on your display adapter.

Q Why is a CPaintDC created and used for WM_PAINT messages instead of a normal CDC object?

A The CPaintDC class is exactly like the CDC class, except that its constructor and destructor do some extra work that is needed when handling a WM_PAINT message. This extra work tells Windows that the window has been repainted. If a CDC object is used, Windows will not be notified that the window has been repainted, and will continue to send WM_PAINT messages.

Workshop

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."

Quiz

1. What is the difference between a device context and an information device context?

2. What CDC member function is used to select a stock object?

3. How many twips are in an inch?

4. What type of GDI object is used to draw lines?

5. What type of GDI object is used to fill areas?

6. How do you determine the height and other characteristics of characters in the currently selected font?

7. What is the RGB macro used for?

8. What MFC class is used as a base class for all device contexts?

9. How can you tell that a call to SelectObject has failed?

10. What mapping mode maps 1 device pixel per measurement unit?

Exercises

1. Modify the DCTest program to change the color for each line of output.

2. Modify the DCTest program so that every line starts with its x and y coordinates.


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.