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 section, you will learn
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.
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 |
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 Section 21, "Printing."
In order to achieve true hardware independence, you must take a few precautions:
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.
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.
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.
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.
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 section.
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:
MM_ANISOTROPIC MM_HIENGLISH MM_HIMETRIC MM_ISOTROPIC MM_LOENGLISH MM_LOMETRIC MM_TEXT MM_TWIPS
| 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"
int cxLog = pDC->GetDeviceCaps( LOGPIXELSX );Later this section 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 Section 21 you will see how GetDeviceCaps is used to determine whether a printer can have bitmaps transferred to it.
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;
// 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.
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);
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.
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?
2. Modify the DCTest program so that every line starts with its x and y coordinates.
Download Sample Programs - DCTest.zip
|
|
|
|