Share via


CDC Class

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CDC Class.

Defines a class of device-context objects.

Syntax

class CDC : public CObject  

Members

Public Constructors

Name Description
CDC::CDC Constructs a CDC object.

Public Methods

Name Description
CDC::AbortDoc Terminates the current print job, erasing everything the application has written to the device since the last call of the StartDoc member function.
CDC::AbortPath Closes and discards any paths in the device context.
CDC::AddMetaFileComment Copies the comment from a buffer into a specified enhanced-format metafile.
CDC::AlphaBlend Displays bitmaps that have transparent or semitransparent pixels.
CDC::AngleArc Draws a line segment and an arc, and moves the current position to the ending point of the arc.
CDC::Arc Draws an elliptical arc.
CDC::ArcTo Draws an elliptical arc. This function is similar to Arc, except that the current position is updated.
CDC::Attach Attaches a Windows device context to this CDC object.
CDC::BeginPath Opens a path bracket in the device context.
CDC::BitBlt Copies a bitmap from a specified device context.
CDC::Chord Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment).
CDC::CloseFigure Closes an open figure in a path.
CDC::CreateCompatibleDC Creates a memory-device context that is compatible with another device context. You can use it to prepare images in memory.
CDC::CreateDC Creates a device context for a specific device.
CDC::CreateIC Creates an information context for a specific device. This provides a fast way to get information about the device without creating a device context.
CDC::DeleteDC Deletes the Windows device context associated with this CDC object.
CDC::DeleteTempMap Called by the CWinApp idle-time handler to delete any temporary CDC object created by FromHandle. Also detaches the device context.
CDC::Detach Detaches the Windows device context from this CDC object.
CDC::DPtoHIMETRIC Converts device units into HIMETRIC units.
CDC::DPtoLP Converts device units into logical units.
CDC::Draw3dRect Draws a three-dimensional rectangle.
CDC::DrawDragRect Erases and redraws a rectangle as it is dragged.
CDC::DrawEdge Draws the edges of a rectangle.
CDC::DrawEscape Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI).
CDC::DrawFocusRect Draws a rectangle in the style used to indicate focus.
CDC::DrawFrameControl Draw a frame control.
CDC::DrawIcon Draws an icon.
CDC::DrawState Displays an image and applies a visual effect to indicate a state.
CDC::DrawText Draws formatted text in the specified rectangle.
CDC::DrawTextEx Draws formatted text in the specified rectangle using additional formats.
CDC::Ellipse Draws an ellipse.
CDC::EndDoc Ends a print job started by the StartDoc member function.
CDC::EndPage Informs the device driver that a page is ending.
CDC::EndPath Closes a path bracket and selects the path defined by the bracket into the device context.
CDC::EnumObjects Enumerates the pens and brushes available in a device context.
CDC::Escape Allows applications to access facilities that are not directly available from a particular device through GDI. Also allows access to Windows escape functions. Escape calls made by an application are translated and sent to the device driver.
CDC::ExcludeClipRect Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.
CDC::ExcludeUpdateRgn Prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region.
CDC::ExtFloodFill Fills an area with the current brush. Provides more flexibility than the CDC::FloodFill member function.
CDC::ExtTextOut Writes a character string within a rectangular region using the currently selected font.
CDC::FillPath Closes any open figures in the current path and fills the path's interior by using the current brush and polygon-filling mode.
CDC::FillRect Fills a given rectangle by using a specific brush.
CDC::FillRgn Fills a specific region with the specified brush.
CDC::FillSolidRect Fills a rectangle with a solid color.
CDC::FlattenPath Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines.
CDC::FloodFill Fills an area with the current brush.
CDC::FrameRect Draws a border around a rectangle.
CDC::FrameRgn Draws a border around a specific region using a brush.
CDC::FromHandle Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached.
CDC::GetArcDirection Returns the current arc direction for the device context.
CDC::GetAspectRatioFilter Retrieves the setting for the current aspect-ratio filter.
CDC::GetBkColor Retrieves the current background color.
CDC::GetBkMode Retrieves the background mode.
CDC::GetBoundsRect Returns the current accumulated bounding rectangle for the specified device context.
CDC::GetBrushOrg Retrieves the origin of the current brush.
CDC::GetCharABCWidths Retrieves the widths, in logical units, of consecutive characters in a given range from the current font.
CDC::GetCharABCWidthsI Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font.
CDC::GetCharacterPlacement Retrieves various types of information on a character string.
CDC::GetCharWidth Retrieves the fractional widths of consecutive characters in a given range from the current font.
CDC::GetCharWidthI Retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font.
CDC::GetClipBox Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary.
CDC::GetColorAdjustment Retrieves the color adjustment values for the device context.
CDC::GetCurrentBitmap Returns a pointer to the currently selected CBitmap object.
CDC::GetCurrentBrush Returns a pointer to the currently selected CBrush object.
CDC::GetCurrentFont Returns a pointer to the currently selected CFont object.
CDC::GetCurrentPalette Returns a pointer to the currently selected CPalette object.
CDC::GetCurrentPen Returns a pointer to the currently selected CPen object.
CDC::GetCurrentPosition Retrieves the current position of the pen (in logical coordinates).
CDC::GetDCBrushColor Retrieves the current brush color.
CDC::GetDCPenColor Retrieves the current pen color.
CDC::GetDeviceCaps Retrieves a specified kind of device-specific information about a given display device's capabilities.
CDC::GetFontData Retrieves font metric information from a scalable font file. The information to retrieve is identified by specifying an offset into the font file and the length of the information to return.
CDC::GetFontLanguageInfo Returns information about the currently selected font for the specified display context.
CDC::GetGlyphOutline Retrieves the outline curve or bitmap for an outline character in the current font.
CDC::GetGraphicsMode Retrieves the current graphics mode for the specified device context.
CDC::GetHalftoneBrush Retrieves a halftone brush.
CDC::GetKerningPairs Retrieves the character kerning pairs for the font that is currently selected in the specified device context.
CDC::GetLayout Retrieves the layout of a device context (DC). The layout can be either left to right (default) or right to left (mirrored).
CDC::GetMapMode Retrieves the current mapping mode.
CDC::GetMiterLimit Returns the miter limit for the device context.
CDC::GetNearestColor Retrieves the closest logical color to a specified logical color that the given device can represent.
CDC::GetOutlineTextMetrics Retrieves font metric information for TrueType fonts.
CDC::GetOutputCharWidth Retrieves the widths of individual characters in a consecutive group of characters from the current font using the output device context.
CDC::GetOutputTabbedTextExtent Computes the width and height of a character string on the output device context.
CDC::GetOutputTextExtent Computes the width and height of a line of text on the output device context using the current font to determine the dimensions.
CDC::GetOutputTextMetrics Retrieves the metrics for the current font from the output device context.
CDC::GetPath Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context.
CDC::GetPixel Retrieves the RGB color value of the pixel at the specified point.
CDC::GetPolyFillMode Retrieves the current polygon-filling mode.
CDC::GetROP2 Retrieves the current drawing mode.
CDC::GetSafeHdc Returns CDC::m_hDC, the output device context.
CDC::GetStretchBltMode Retrieves the current bitmap-stretching mode.
CDC::GetTabbedTextExtent Computes the width and height of a character string on the attribute device context.
CDC::GetTextAlign Retrieves the text-alignment flags.
CDC::GetTextCharacterExtra Retrieves the current setting for the amount of intercharacter spacing.
CDC::GetTextColor Retrieves the current text color.
CDC::GetTextExtent Computes the width and height of a line of text on the attribute device context using the current font to determine the dimensions.
CDC::GetTextExtentExPointI Retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters.
CDC::GetTextExtentPointI Retrieves the width and height of the specified array of glyph indices.
CDC::GetTextFace Copies the typeface name of the current font into a buffer as a null-terminated string.
CDC::GetTextMetrics Retrieves the metrics for the current font from the attribute device context.
CDC::GetViewportExt Retrieves the x- and y-extents of the viewport.
CDC::GetViewportOrg Retrieves the x- and y-coordinates of the viewport origin.
CDC::GetWindow Returns the window associated with the display device context.
CDC::GetWindowExt Retrieves the x- and y-extents of the associated window.
CDC::GetWindowOrg Retrieves the x- and y-coordinates of the origin of the associated window.
CDC::GetWorldTransform Retrieves the current world-space to page-space transformation.
CDC::GradientFill Fills rectangle and triangle structures with a gradating color.
CDC::GrayString Draws dimmed (grayed) text at the given location.
CDC::HIMETRICtoDP Converts HIMETRIC units into device units.
CDC::HIMETRICtoLP Converts HIMETRIC units into logical units.
CDC::IntersectClipRect Creates a new clipping region by forming the intersection of the current region and a rectangle.
CDC::InvertRect Inverts the contents of a rectangle.
CDC::InvertRgn Inverts the colors in a region.
CDC::IsPrinting Determines whether the device context is being used for printing.
CDC::LineTo Draws a line from the current position up to, but not including, a point.
CDC::LPtoDP Converts logical units into device units.
CDC::LPtoHIMETRIC Converts logical units into HIMETRIC units.
CDC::MaskBlt Combines the color data for the source and destination bitmaps using the given mask and raster operation.
CDC::ModifyWorldTransform Changes the world transformation for a device context using the specified mode.
CDC::MoveTo Moves the current position.
CDC::OffsetClipRgn Moves the clipping region of the given device.
CDC::OffsetViewportOrg Modifies the viewport origin relative to the coordinates of the current viewport origin.
CDC::OffsetWindowOrg Modifies the window origin relative to the coordinates of the current window origin.
CDC::PaintRgn Fills a region with the selected brush.
CDC::PatBlt Creates a bit pattern.
CDC::Pie Draws a pie-shaped wedge.
CDC::PlayMetaFile Plays the contents of the specified metafile on the given device. The enhanced version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. The metafile can be played any number of times.
CDC::PlgBlt Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context.
CDC::PolyBezier Draws one or more Bzier splines. The current position is neither used nor updated.
CDC::PolyBezierTo Draws one or more Bzier splines, and moves the current position to the ending point of the last Bzier spline.
CDC::PolyDraw Draws a set of line segments and Bzier splines. This function updates the current position.
CDC::Polygon Draws a polygon consisting of two or more points (vertices) connected by lines.
CDC::Polyline Draws a set of line segments connecting the specified points.
CDC::PolylineTo Draws one or more straight lines and moves the current position to the ending point of the last line.
CDC::PolyPolygon Creates two or more polygons that are filled using the current polygon-filling mode. The polygons may be disjoint or they may overlap.
CDC::PolyPolyline Draws multiple series of connected line segments. The current position is neither used nor updated by this function.
CDC::PtVisible Specifies whether the given point is within the clipping region.
CDC::RealizePalette Maps palette entries in the current logical palette to the system palette.
CDC::Rectangle Draws a rectangle using the current pen and fills it using the current brush.
CDC::RectVisible Determines whether any part of the given rectangle lies within the clipping region.
CDC::ReleaseAttribDC Releases m_hAttribDC, the attribute device context.
CDC::ReleaseOutputDC Releases m_hDC, the output device context.
CDC::ResetDC Updates the m_hAttribDC device context.
CDC::RestoreDC Restores the device context to a previous state saved with SaveDC.
CDC::RoundRect Draws a rectangle with rounded corners using the current pen and filled using the current brush.
CDC::SaveDC Saves the current state of the device context.
CDC::ScaleViewportExt Modifies the viewport extent relative to the current values.
CDC::ScaleWindowExt Modifies the window extents relative to the current values.
CDC::ScrollDC Scrolls a rectangle of bits horizontally and vertically.
CDC::SelectClipPath Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode.
CDC::SelectClipRgn Combines the given region with the current clipping region by using the specified mode.
CDC::SelectObject Selects a GDI drawing object such as a pen.
CDC::SelectPalette Selects the logical palette.
CDC::SelectStockObject Selects one of the predefined stock pens, brushes, or fonts provided by Windows.
CDC::SetAbortProc Sets a programmer-supplied callback function that Windows calls if a print job must be aborted.
CDC::SetArcDirection Sets the drawing direction to be used for arc and rectangle functions.
CDC::SetAttribDC Sets m_hAttribDC, the attribute device context.
CDC::SetBkColor Sets the current background color.
CDC::SetBkMode Sets the background mode.
CDC::SetBoundsRect Controls the accumulation of bounding-rectangle information for the specified device context.
CDC::SetBrushOrg Specifies the origin for the next brush selected into a device context.
CDC::SetColorAdjustment Sets the color adjustment values for the device context using the specified values.
CDC::SetDCBrushColor Sets the current brush color.
CDC::SetDCPenColor Sets the current pen color.
CDC::SetGraphicsMode Sets the current graphics mode for the specified device context.
CDC::SetLayout Changes the layout of a device context (DC).
CDC::SetMapMode Sets the current mapping mode.
CDC::SetMapperFlags Alters the algorithm that the font mapper uses when it maps logical fonts to physical fonts.
CDC::SetMiterLimit Sets the limit for the length of miter joins for the device context.
CDC::SetOutputDC Sets m_hDC, the output device context.
CDC::SetPixel Sets the pixel at the specified point to the closest approximation of the specified color.
CDC::SetPixelV Sets the pixel at the specified coordinates to the closest approximation of the specified color. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.
CDC::SetPolyFillMode Sets the polygon-filling mode.
CDC::SetROP2 Sets the current drawing mode.
CDC::SetStretchBltMode Sets the bitmap-stretching mode.
CDC::SetTextAlign Sets the text-alignment flags.
CDC::SetTextCharacterExtra Sets the amount of intercharacter spacing.
CDC::SetTextColor Sets the text color.
CDC::SetTextJustification Adds space to the break characters in a string.
CDC::SetViewportExt Sets the x- and y-extents of the viewport.
CDC::SetViewportOrg Sets the viewport origin.
CDC::SetWindowExt Sets the x- and y-extents of the associated window.
CDC::SetWindowOrg Sets the window origin of the device context.
CDC::SetWorldTransform Sets the current world-space to page-space transformation.
CDC::StartDoc Informs the device driver that a new print job is starting.
CDC::StartPage Informs the device driver that a new page is starting.
CDC::StretchBlt Moves a bitmap from a source rectangle and device into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle.
CDC::StrokeAndFillPath Closes any open figures in a path, strikes the outline of the path by using the current pen, and fills its interior by using the current brush.
CDC::StrokePath Renders the specified path by using the current pen.
CDC::TabbedTextOut Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions.
CDC::TextOut Writes a character string at a specified location using the currently selected font.
CDC::TransparentBlt Transfers a bit-block of color data from the specified source device context into a destination device context, rendering a specified color transparent in the transfer.
CDC::UpdateColors Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis.
CDC::WidenPath Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context.

Public Operators

Name Description
CDC::operator HDC Retrieves the handle of the device context.

Public Data Members

Name Description
CDC::m_hAttribDC The attribute-device context used by this CDC object.
CDC::m_hDC The output-device context used by this CDC object.

Remarks

The CDC object provides member functions for working with a device context, such as a display or printer, as well as members for working with a display context associated with the client area of a window.

Do all drawing through the member functions of a CDC object. The class provides member functions for device-context operations, working with drawing tools, type-safe graphics device interface (GDI) object selection, and working with colors and palettes. It also provides member functions for getting and setting drawing attributes, mapping, working with the viewport, working with the window extent, converting coordinates, working with regions, clipping, drawing lines, and drawing simple shapes, ellipses, and polygons. Member functions are also provided for drawing text, working with fonts, using printer escapes, scrolling, and playing metafiles.

To use a CDC object, construct it, and then call its member functions that parallel Windows functions that use device contexts.

Note

Under Windows 95/98, all screen coordinates are limited to 16 bits. Therefore, an int passed to a CDC member function must lie in the range –32768 to 32767.

For specific uses, the Microsoft Foundation Class Library provides several classes derived from CDC . CPaintDC encapsulates calls to BeginPaint and EndPaint. CClientDC manages a display context associated with a window's client area. CWindowDC manages a display context associated with an entire window, including its frame and controls. CMetaFileDC associates a device context with a metafile.

CDC provides two member functions, GetLayout and SetLayout, for reversing the layout of a device context, which does not inherit its layout from a window. Such right-to-left orientation is necessary for applications written for cultures, such as Arabic or Hebrew, where the character layout is not the European standard.

CDC contains two device contexts, m_hDC and m_hAttribDC, which, on creation of a CDC object, refer to the same device. CDC directs all output GDI calls to m_hDC and most attribute GDI calls to m_hAttribDC. (An example of an attribute call is GetTextColor, while SetTextColor is an output call.)

For example, the framework uses these two device contexts to implement a CMetaFileDC object that will send output to a metafile while reading attributes from a physical device. Print preview is implemented in the framework in a similar fashion. You can also use the two device contexts in a similar way in your application-specific code.

There are times when you may need text-metric information from both the m_hDC and m_hAttribDC device contexts. The following pairs of functions provide this capability:

Uses m_hAttribDC Uses m_hDC
GetTextExtent GetOutputTextExtent
GetTabbedTextExtent GetOutputTabbedTextExtent
GetTextMetrics GetOutputTextMetrics
GetCharWidth GetOutputCharWidth

For more information on CDC, see Device Contexts.

Inheritance Hierarchy

CObject

CDC

Requirements

Header: afxwin.h

CDC::AbortDoc

Terminates the current print job and erases everything the application has written to the device since the last call to the StartDoc member function.

int AbortDoc();

Return Value

A value greater than or equal to 0 if successful, or a negative value if an error has occurred. The following list shows common error values and their meanings:

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User terminated the job through the Print Manager.

Remarks

This member function replaces the ABORTDOC printer escape.

AbortDoc should be used to terminate the following:

  • Printing operations that do not specify an abort function using SetAbortProc.

  • Printing operations that have not yet reached their first NEWFRAME or NEXTBAND escape call.

If an application encounters a printing error or a canceled print operation, it must not attempt to terminate the operation by using either the EndDoc or AbortDoc member functions of class CDC. GDI automatically terminates the operation before returning the error value.

If the application displays a dialog box to allow the user to cancel the print operation, it must call AbortDoc before destroying the dialog box.

If Print Manager was used to start the print job, calling AbortDoc erases the entire spool job — the printer receives nothing. If Print Manager was not used to start the print job, the data may have been sent to the printer before AbortDoc was called. In this case, the printer driver would have reset the printer (when possible) and closed the print job.

Example

See the example for CDC::StartDoc.

CDC::AbortPath

Closes and discards any paths in the device context.

BOOL AbortPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

If there is an open path bracket in the device context, the path bracket is closed and the path is discarded. If there is a closed path in the device context, the path is discarded.

CDC::AddMetaFileComment

Copies the comment from a buffer into a specified enhanced-format metafile.

BOOL AddMetaFileComment(
    UINT nDataSize,  
    const BYTE* pCommentData);

Parameters

nDataSize
Specifies the length of the comment buffer, in bytes.

pCommentData
Points to the buffer that contains the comment.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

A comment may include any private information — for example, the source of the picture and the date it was created. A comment should begin with an application signature, followed by the data. Comments should not contain position-specific data. Position-specific data specifies the location of a record, and it should not be included because one metafile may be embedded within another metafile. This function can only be used with enhanced metafiles.

CDC::AlphaBlend

Call this member function to display bitmaps that have transparent or semitransparent pixels.

BOOL AlphaBlend(
    int xDest,  
    int yDest,  
    int nDestWidth,  
    int nDestHeight,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    int nSrcWidth,  
    int nSrcHeight,  
    BLENDFUNCTION blend);

Parameters

xDest
Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.

yDest
Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.

nDestWidth
Specifies the width, in logical units, of the destination rectangle.

nDestHeight
Specifies the height, in logical units, of the destination rectangle.

pSrcDC
A pointer to the source device context.

xSrc
Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.

ySrc
Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.

nSrcWidth
Specifies the width, in logical units, of the source rectangle.

nSrcHeight
Specifies the height, in logical units, of the source rectangle.

blend
Specifies a BLENDFUNCTION structure.

Return Value

TRUE if successful; otherwise FALSE.

Remarks

See AlphaBlend in the Windows SDK for more information.

CDC::AngleArc

Draws a line segment and an arc.

BOOL AngleArc(
    int x,  
    int y,  
    int nRadius,  
    float fStartAngle,  
    float fSweepAngle);

Parameters

x
Specifies the logical x-coordinate of the center of the circle.

y
Specifies the logical y-coordinate of the center of the circle.

nRadius
Specifies the radius of the circle in logical units. This value must be positive.

fStartAngle
Specifies the starting angle in degrees relative to the x-axis.

fSweepAngle
Specifies the sweep angle in degrees relative to the starting angle.

Return Value

Nonzero if successful; otherwise 0.

Remarks

The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the given radius and center. The length of the arc is defined by the given start and sweep angles.

AngleArc moves the current position to the ending point of the arc. The arc drawn by this function may appear to be elliptical, depending on the current transformation and mapping mode. Before drawing the arc, this function draws the line segment from the current position to the beginning of the arc. The arc is drawn by constructing an imaginary circle with the specified radius around the specified center point. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees in the start angle. The ending point is similarly located by measuring counterclockwise from the starting point by the number of degrees in the sweep angle.

If the sweep angle is greater than 360 degrees the arc is swept multiple times. This function draws lines by using the current pen. The figure is not filled.

CDC::Arc

Draws an elliptical arc.

BOOL Arc(
    int x1,  
    int y1,  
    int x2,  
    int y2,  
    int x3,  
    int y3,  
    int x4,  
    int y4);

 
BOOL Arc(
    LPCRECT lpRect,  
    POINT ptStart,  
    POINT ptEnd);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3
Specifies the x-coordinate of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

y3
Specifies the y-coordinate of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

x4
Specifies the x-coordinate of the point that defines the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

y4
Specifies the y-coordinate of the point that defines the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect
Specifies the bounding rectangle (in logical units). You can pass either an LPRECT or a CRect object for this parameter.

ptStart
Specifies the x- and y-coordinates of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd
Specifies the x- and y-coordinates of the point that defines the arc's ending point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The arc drawn by using the function is a segment of the ellipse defined by the specified bounding rectangle.

The actual starting point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified starting point intersects the ellipse. The actual ending point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified ending point intersects the ellipse. The arc is drawn in a counterclockwise direction. Since an arc is not a closed figure, it is not filled. Both the width and height of the rectangle must be greater than 2 units and less than 32,767 units.

Example

void CDCView::DrawArc(CDC* pDC)
{
   // Fill the client area with a thin circle. The circle's
   // interior is not filled. The circle's perimeter is
   // blue from 6 o'clock to 3 o'clock and red from 3
   // o'clock to 6 o'clock.

   // Get the client area.
   CRect rectClient;
   GetClientRect(rectClient);

   // Make a couple of pens.
   CPen penBlue;
   CPen penRed;
   CPen* pOldPen;

   penBlue.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(0, 0, 255));
   penRed.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(255, 0, 0));

   // Draw from 3 o'clock to 6 o'clock, counterclockwise,
   // in a blue pen.

   pOldPen = pDC->SelectObject(&penBlue);

   pDC->Arc(rectClient,
      CPoint(rectClient.right, rectClient.CenterPoint().y),
      CPoint(rectClient.CenterPoint().x, rectClient.right));

   // Draw from 6 o'clock to 3 o'clock, counterclockwise,
   // in a red pen.
   pDC->SelectObject(&penRed);

   // Keep the same parameters, but reverse start
   // and end points.
   pDC->Arc(rectClient,
      CPoint(rectClient.CenterPoint().x, rectClient.right),
      CPoint(rectClient.right, rectClient.CenterPoint().y));

   // Restore the previous pen.
   pDC->SelectObject(pOldPen);
}

CDC::ArcTo

Draws an elliptical arc.

BOOL ArcTo(
    int x1,  
    int y1,  
    int x2,  
    int y2,  
    int x3,  
    int y3,  
    int x4,  
    int y4);

 
BOOL ArcTo(
    LPCRECT lpRect,  
    POINT ptStart,  
    POINT ptEnd);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3
Specifies the x-coordinate of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

y3
Specifies the y-coordinate of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

x4
Specifies the x-coordinate of the point that defines the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

y4
Specifies the y-coordinate of the point that defines the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect
Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT data structure or a CRect object for this parameter.

ptStart
Specifies the x- and y-coordinates of the point that defines the arc's starting point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT data structure or a CPoint object for this parameter.

ptEnd
Specifies the x- and y-coordinates of the point that defines the arc's ending point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT data structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This function is similar to CDC::Arc, except that the current position is updated. The points ( x1, y1) and ( x2, y2) specify the bounding rectangle. An ellipse formed by the given bounding rectangle defines the curve of the arc. The arc extends counterclockwise (the default arc direction) from the point where it intersects the radial line from the center of the bounding rectangle to ( x3, y3). The arc ends where it intersects the radial line from the center of the bounding rectangle to ( x4, y4). If the starting point and ending point are the same, a complete ellipse is drawn.

A line is drawn from the current position to the starting point of the arc. If no error occurs, the current position is set to the ending point of the arc. The arc is drawn using the current pen; it is not filled.

CDC::Attach

Use this member function to attach an hDC to the CDC object.

BOOL Attach(HDC hDC);

Parameters

hDC
A Windows device context.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The hDC is stored in both m_hDC, the output device context, and in m_hAttribDC, the attribute device context.

CDC::BeginPath

Opens a path bracket in the device context.

BOOL BeginPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

After a path bracket is open, an application can begin calling GDI drawing functions to define the points that lie in the path. An application can close an open path bracket by calling the EndPath member function. When an application calls BeginPath, any previous paths are discarded.

See BeginPath in the Windows SDK for a list of the drawing functions that define points in a path.

Example

// This implementation uses GDI paths to draw the outline of
// some text in a TrueType font. The path is used to record the way
// the TrueType font would be drawn. Then, the function uses the data
// returned from CDC::GetPath() to draw the font--without filling it.
void CDCView::DrawPath(CDC* pDC)
{
   // Describe a 24-point truetype font of normal weight
   LOGFONT lf;
   memset(&lf, 0, sizeof(lf));
   lf.lfHeight = -MulDiv(24, pDC->GetDeviceCaps(LOGPIXELSY), 72);
   lf.lfWeight = FW_NORMAL;
   lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;

   // create and select it
   CFont newFont;
   if (!newFont.CreateFontIndirect(&lf))
      return;
   CFont* pOldFont = pDC->SelectObject(&newFont);

   // use a path to record how the text was drawn
   pDC->BeginPath();
   pDC->TextOut(10, 10, _T("Outline this!"));
   pDC->EndPath();

   // Find out how many points are in the path. Note that
   // for long strings or complex fonts, this number might be
   // gigantic!
   int nNumPts = pDC->GetPath(NULL, NULL, 0);
   if (nNumPts == 0)
      return;

   // Allocate memory to hold points and stroke types from
   // the path.
   LPPOINT lpPoints = NULL;
   LPBYTE lpTypes = NULL;
   try
   {
      lpPoints = new POINT[nNumPts];
      lpTypes = new BYTE[nNumPts];
   }
   catch (CException* pe)
   {
      delete [] lpPoints;
      lpPoints = NULL;
      delete [] lpTypes;
      lpTypes = NULL;
      pe->Delete();  
   }
   if (lpPoints == NULL || lpTypes == NULL)
      return;

   // Now that we have the memory, really get the path data.
   nNumPts = pDC->GetPath(lpPoints, lpTypes, nNumPts);

   // If it worked, draw the lines. Windows 98 doesn't support
   // the PolyDraw API, so we use our own member function to do
   // similar work. If you're targeting only later versions of 
   // Windows, you can use the PolyDraw() API and avoid the 
   // COutlineView::PolyDraw() member function.

   if (nNumPts != -1)
      pDC->PolyDraw(lpPoints, lpTypes, nNumPts);

   // Release the memory we used
   delete [] lpPoints;
   delete [] lpTypes;

   // Put back the old font
   pDC->SelectObject(pOldFont);

   return;
}

CDC::BitBlt

Copies a bitmap from the source device context to this current device context.

BOOL BitBlt(
    int x,  
    int y,  
    int nWidth,  
    int nHeight,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    DWORD dwRop);

Parameters

x
Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

y
Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth
Specifies the width (in logical units) of the destination rectangle and source bitmap.

nHeight
Specifies the height (in logical units) of the destination rectangle and source bitmap.

pSrcDC
Pointer to a CDC object that identifies the device context from which the bitmap will be copied. It must be NULL if dwRop specifies a raster operation that does not include a source.

xSrc
Specifies the logical x-coordinate of the upper-left corner of the source bitmap.

ySrc
Specifies the logical y-coordinate of the upper-left corner of the source bitmap.

dwRop
Specifies the raster operation to be performed. Raster-operation codes define how the GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. See BitBlt in the Windows SDK for a list of the raster-operation codes for dwRop and their descriptions

For a complete list of raster-operation codes, see About Raster Operation Codes in the Windows SDK.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The application can align the windows or client areas on byte boundaries to ensure that the BitBlt operations occur on byte-aligned rectangles. (Set the CS_BYTEALIGNWINDOW or CS_BYTEALIGNCLIENT flags when you register the window classes.)

BitBlt operations on byte-aligned rectangles are considerably faster than BitBlt operations on rectangles that are not byte aligned. If you want to specify class styles such as byte-alignment for your own device context, you will have to register a window class rather than relying on the Microsoft Foundation classes to do it for you. Use the global function AfxRegisterWndClass.

GDI transforms nWidth and nHeight, once by using the destination device context, and once by using the source device context. If the resulting extents do not match, GDI uses the Windows StretchBlt function to compress or stretch the source bitmap as necessary.

If destination, source, and pattern bitmaps do not have the same color format, the BitBlt function converts the source and pattern bitmaps to match the destination. The foreground and background colors of the destination bitmap are used in the conversion.

When the BitBlt function converts a monochrome bitmap to color, it sets white bits (1) to the background color and black bits (0) to the foreground color. The foreground and background colors of the destination device context are used. To convert color to monochrome, BitBlt sets pixels that match the background color to white and sets all other pixels to black. BitBlt uses the foreground and background colors of the color device context to convert from color to monochrome.

Note that not all device contexts support BitBlt. To check whether a given device context does support BitBlt, use the GetDeviceCaps member function and specify the RASTERCAPS index.

Example

See the example for CDC::CreateCompatibleDC.

CDC::CDC

Constructs a CDC object.

CDC();

CDC::Chord

Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment).

BOOL Chord(
    int x1,  
    int y1,  
    int x2,  
    int y2,  
    int x3,  
    int y3,  
    int x4,  
    int y4);

 
BOOL Chord(
    LPCRECT lpRect,  
    POINT ptStart,  
    POINT ptEnd);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the chord's bounding rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the chord's bounding rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the chord's bounding rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the chord's bounding rectangle (in logical units).

x3
Specifies the x-coordinate of the point that defines the chord's starting point (in logical units).

y3
Specifies the y-coordinate of the point that defines the chord's starting point (in logical units).

x4
Specifies the x-coordinate of the point that defines the chord's endpoint (in logical units).

y4
Specifies the y-coordinate of the point that defines the chord's endpoint (in logical units).

lpRect
Specifies the bounding rectangle (in logical units). You can pass either a LPRECT or a CRect object for this parameter.

ptStart
Specifies the x- and y-coordinates of the point that defines the chord's starting point (in logical units). This point does not have to lie exactly on the chord. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd
Specifies the x- and y-coordinates of the point that defines the chord's ending point (in logical units). This point does not have to lie exactly on the chord. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The ( x1, y1) and ( x2, y2) parameters specify the upper-left and lower-right corners, respectively, of a rectangle bounding the ellipse that is part of the chord. The ( x3, y3) and ( x4, y4) parameters specify the endpoints of a line that intersects the ellipse. The chord is drawn by using the selected pen and filled by using the selected brush.

The figure drawn by the Chord function extends up to, but does not include the right and bottom coordinates. This means that the height of the figure is y2y1 and the width of the figure is x2x1.

Example

void CDCView::DrawChord(CDC* pDC)
{
   // Fill the client area with a circle. The circle is
   // blue and filled with blue, but has a chord cut out
   // of it from 3 o'clock to 6 o'clock. That chord is
   // red and filled with a red diagonal hatch.

   // Get the client area.
   CRect rectClient;
   GetClientRect(rectClient);

   // Make a couple of pens and similar brushes.
   CPen penBlue, penRed;
   CBrush brushBlue, brushRed;
   CBrush* pOldBrush;
   CPen* pOldPen;

   brushBlue.CreateSolidBrush(RGB(0, 0, 255));
   brushRed.CreateHatchBrush(HS_FDIAGONAL, RGB(255, 0, 0));
   penBlue.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(0, 0, 255));
   penRed.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(255, 0, 0));

   // Draw from 3 o'clock to 6 o'clock, counterclockwise,
   // in a blue pen with a solid blue fill.
   pOldPen = pDC->SelectObject(&penBlue);
   pOldBrush = pDC->SelectObject(&brushBlue);

   pDC->Chord(rectClient,
      CPoint(rectClient.right, rectClient.CenterPoint().y),
      CPoint(rectClient.CenterPoint().x, rectClient.right));

   // Draw the remaining quarter chord from 6 o'clock
   // to 3 o'clock, counterclockwise, in a red pen
   // with the hatched brush.
   pDC->SelectObject(&penRed);
   pDC->SelectObject(&brushRed);

   // Keep the same parameters, but reverse start and
   // end points.
   pDC->Chord(rectClient,
      CPoint(rectClient.CenterPoint().x, rectClient.right),
      CPoint(rectClient.right, rectClient.CenterPoint().y));

   // Restore the previous pen.
   pDC->SelectObject(pOldPen);
}

CDC::CloseFigure

Closes an open figure in a path.

BOOL CloseFigure();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The function closes the figure by drawing a line from the current position to the first point of the figure (usually, the point specified by the most recent call to the MoveTo member function) and connects the lines by using the line join style. If a figure is closed by using the LineTo member function instead of CloseFigure, end caps are used to create the corner instead of a join. CloseFigure should only be called if there is an open path bracket in the device context.

A figure in a path is open unless it is explicitly closed by using this function. (A figure can be open even if the current point and the starting point of the figure are the same.) Any line or curve added to the path after CloseFigure starts a new figure.

CDC::CreateCompatibleDC

Creates a memory device context that is compatible with the device specified by pDC.

BOOL CreateCompatibleDC(CDC* pDC);

Parameters

pDC
A pointer to a device context. If pDC is NULL, the function creates a memory device context that is compatible with the system display.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

A memory device context is a block of memory that represents a display surface. It can be used to prepare images in memory before copying them to the actual device surface of the compatible device.

When a memory device context is created, GDI automatically selects a 1-by-1 monochrome stock bitmap for it. GDI output functions can be used with a memory device context only if a bitmap has been created and selected into that context.

This function can only be used to create compatible device contexts for devices that support raster operations. See the CDC::BitBlt member function for information regarding bit-block transfers between device contexts. To determine whether a device context supports raster operations, see the RC_BITBLT raster capability in the member function CDC::GetDeviceCaps.

Example

// This handler loads a bitmap from system resources,
// centers it in the view, and uses BitBlt() to paint the bitmap
// bits.
void CDCView::DrawBitmap(CDC* pDC)
{
   // load IDB_BITMAP1 from our resources
   CBitmap bmp;
   if (bmp.LoadBitmap(IDB_BITMAP1))
   {
      // Get the size of the bitmap
      BITMAP bmpInfo;
      bmp.GetBitmap(&bmpInfo);

      // Create an in-memory DC compatible with the
      // display DC we're using to paint
      CDC dcMemory;
      dcMemory.CreateCompatibleDC(pDC);

      // Select the bitmap into the in-memory DC
      CBitmap* pOldBitmap = dcMemory.SelectObject(&bmp);

      // Find a centerpoint for the bitmap in the client area
      CRect rect;
      GetClientRect(&rect);
      int nX = rect.left + (rect.Width() - bmpInfo.bmWidth) / 2;
      int nY = rect.top + (rect.Height() - bmpInfo.bmHeight) / 2;

      // Copy the bits from the in-memory DC into the on-
      // screen DC to actually do the painting. Use the centerpoint
      // we computed for the target offset.
      pDC->BitBlt(nX, nY, bmpInfo.bmWidth, bmpInfo.bmHeight, &dcMemory, 
         0, 0, SRCCOPY);

      dcMemory.SelectObject(pOldBitmap);
   }
   else
   {
      TRACE0("ERROR: Where's IDB_BITMAP1?\n");
   }
}

CDC::CreateDC

Creates a device context for the specified device.

BOOL CreateDC(
    LPCTSTR lpszDriverName,  
    LPCTSTR lpszDeviceName,  
    LPCTSTR lpszOutput,  
    const void* lpInitData);

Parameters

lpszDriverName
Points to a null-terminated string that specifies the filename (without extension) of the device driver (for example, "EPSON"). You can also pass a CString object for this parameter.

lpszDeviceName
Points to a null-terminated string that specifies the name of the specific device to be supported (for example, "EPSON FX-80"). The lpszDeviceName parameter is used if the module supports more than one device. You can also pass a CString object for this parameter.

lpszOutput
Points to a null-terminated string that specifies the file or device name for the physical output medium (file or output port). You can also pass a CString object for this parameter.

lpInitData
Points to a DEVMODE structure containing device-specific initialization data for the device driver. The Windows DocumentProperties function retrieves this structure filled in for a given device. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user through the Control Panel.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The PRINT.H header file is required if the DEVMODE structure is used.

Device names follow these conventions: an ending colon (:) is recommended, but optional. Windows strips the terminating colon so that a device name ending with a colon is mapped to the same port as the same name without a colon. The driver and port names must not contain leading or trailing spaces. GDI output functions cannot be used with information contexts.

CDC::CreateIC

Creates an information context for the specified device.

BOOL CreateIC(
    LPCTSTR lpszDriverName,  
    LPCTSTR lpszDeviceName,  
    LPCTSTR lpszOutput,  
    const void* lpInitData);

Parameters

lpszDriverName
Points to a null-terminated string that specifies the filename (without extension) of the device driver (for example, "EPSON"). You can pass a CString object for this parameter.

lpszDeviceName
Points to a null-terminated string that specifies the name of the specific device to be supported (for example, "EPSON FX-80"). The lpszDeviceName parameter is used if the module supports more than one device. You can pass a CString object for this parameter.

lpszOutput
Points to a null-terminated string that specifies the file or device name for the physical output medium (file or port). You can pass a CString object for this parameter.

lpInitData
Points to device-specific initialization data for the device driver. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user through the Control Panel. See CreateDC for the data format for device-specific initialization.

Return Value

Nonzero if successful; otherwise 0.

Remarks

The information context provides a fast way to get information about the device without creating a device context.

Device names follow these conventions: an ending colon (:) is recommended, but optional. Windows strips the terminating colon so that a device name ending with a colon is mapped to the same port as the same name without a colon. The driver and port names must not contain leading or trailing spaces. GDI output functions cannot be used with information contexts.

CDC::DeleteDC

In general, do not call this function; the destructor will do it for you.

BOOL DeleteDC();

Return Value

Nonzero if the function completed successfully; otherwise 0.

Remarks

The DeleteDC member function deletes the Windows device contexts that are associated with m_hDC in the current CDC object. If this CDC object is the last active device context for a given device, the device is notified and all storage and system resources used by the device are released.

An application should not call DeleteDC if objects have been selected into the device context. Objects must first be selected out of the device context before it is deleted.

An application must not delete a device context whose handle was obtained by calling CWnd::GetDC. Instead, it must call CWnd::ReleaseDC to free the device context. The CClientDC and CWindowDC classes are provided to wrap this functionality.

The DeleteDC function is generally used to delete device contexts created with CreateDC, CreateIC, or CreateCompatibleDC.

Example

See the example for CPrintDialog::GetPrinterDC.

CDC::DeleteTempMap

Called automatically by the CWinApp idle-time handler, DeleteTempMap deletes any temporary CDC objects created by FromHandle, but does not destroy the device context handles ( hDCs) temporarily associated with the CDC objects.

static void PASCAL DeleteTempMap();

CDC::Detach

Call this function to detach m_hDC (the output device context) from the CDC object and set both m_hDC and m_hAttribDC to NULL.

HDC Detach();

Return Value

A Windows device context.

CDC::DPtoHIMETRIC

Use this function when you give HIMETRIC sizes to OLE, converting pixels to HIMETRIC.

void DPtoHIMETRIC(LPSIZE lpSize) const;  

Parameters

lpSize
Points to a SIZE structure or CSize object.

Remarks

If the mapping mode of the device context object is MM_LOENGLISH, MM_HIENGLISH, MM_LOMETRIC, or MM_HIMETRIC, then the conversion is based on the number of pixels in the physical inch. If the mapping mode is one of the other non-constrained modes (e.g., MM_TEXT), then the conversion is based on the number of pixels in the logical inch.

CDC::DPtoLP

Converts device units into logical units.

void DPtoLP(
    LPPOINT lpPoints,  
    int nCount = 1) const;  
  
void DPtoLP(LPRECT lpRect) const;
void DPtoLP(LPSIZE lpSize) const;  

Parameters

lpPoints
Points to an array of POINT structures or CPoint objects.

nCount
The number of points in the array.

lpRect
Points to a RECT structure or CRect object. This parameter is used for the simple case of converting one rectangle from device points to logical points.

lpSize
Points to a SIZE structure or CSize object.

Remarks

The function maps the coordinates of each point, or dimension of a size, from the device coordinate system into GDI's logical coordinate system. The conversion depends on the current mapping mode and the settings of the origins and extents for the device's window and viewport.

CDC::Draw3dRect

Call this member function to draw a three-dimensional rectangle.

void Draw3dRect(
    LPCRECT lpRect,  
    COLORREF clrTopLeft,  
    COLORREF clrBottomRight);

 
void Draw3dRect(
    int x,  
    int y,  
    int cx,  
    int cy,  
    COLORREF clrTopLeft,  
    COLORREF clrBottomRight);

Parameters

lpRect
Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT structure or a CRect object for this parameter.

clrTopLeft
Specifies the color of the top and left sides of the three-dimensional rectangle.

clrBottomRight
Specifies the color of the bottom and right sides of the three-dimensional rectangle.

x
Specifies the logical x-coordinate of the upper-left corner of the three-dimensional rectangle.

y
Specifies the logical y-coordinate of the upper-left corner of the three-dimensional rectangle.

cx
Specifies the width of the three-dimensional rectangle.

cy
Specifies the height of the three-dimensional rectangle.

Remarks

The rectangle will be drawn with the top and left sides in the color specified by clrTopLeft and the bottom and right sides in the color specified by clrBottomRight.

Example

void CDCView::Draw3dRect(CDC* pDC)
{
   // get the client area
   CRect rect;
   GetClientRect(rect);

   // shrink our rect 20 pixels on all sides
   rect.DeflateRect(20, 20);

   // draw a rectangle with red top and left sides, and
   // green right and bottom sides.
   pDC->Draw3dRect(rect, RGB(255, 0, 0), RGB(0, 255, 0));

   // This call to the four-integer override would draw
   // the same rectangle with a little less convenience:

   // pDC->Draw3dRect(rect.left, rect.top, rect.Width(), rect.Height(),
   //    RGB(255, 0, 0), RGB(0, 255, 0));
}

CDC::DrawDragRect

Call this member function repeatedly to redraw a drag rectangle.

void DrawDragRect(
    LPCRECT lpRect,  
    SIZE size,  
    LPCRECT lpRectLast,  
    SIZE sizeLast,  
    CBrush* pBrush = NULL,  
    CBrush* pBrushLast = NULL);

Parameters

lpRect
Points to a RECT structure or a CRect object that specifies the logical coordinates of a rectangle — in this case, the end position of the rectangle being redrawn.

size
Specifies the displacement from the top-left corner of the outer border to the top-left corner of the inner border (that is, the thickness of the border) of a rectangle.

lpRectLast
Points to a RECT structure or a CRect object that specifies the logical coordinates of the position of a rectangle — in this case, the original position of the rectangle being redrawn.

sizeLast
Specifies the displacement from the top-left corner of the outer border to the top-left corner of the inner border (that is, the thickness of the border) of the original rectangle being redrawn.

pBrush
Pointer to a brush object. Set to NULL to use the default halftone brush.

pBrushLast
Pointer to the last brush object used. Set to NULL to use the default halftone brush.

Remarks

Call it in a loop as you sample mouse position, in order to give visual feedback. When you call DrawDragRect, the previous rectangle is erased and a new one is drawn. For example, as the user drags a rectangle across the screen, DrawDragRect will erase the original rectangle and redraw a new one in its new position. By default, DrawDragRect draws the rectangle by using a halftone brush to eliminate flicker and to create the appearance of a smoothly moving rectangle.

The first time you call DrawDragRect, the lpRectLast parameter should be NULL.

CDC::DrawEdge

Call this member function to draw the edges of a rectangle of the specified type and style.

BOOL DrawEdge(
    LPRECT lpRect,  
    UINT nEdge,  
    UINT nFlags);

Parameters

lpRect
A pointer to a RECT structure that contains the logical coordinates of the rectangle.

nEdge
Specifies the type of inner and outer edge to draw. This parameter must be a combination of one inner-border flag and one outer-border flag. See DrawEdge in the Windows SDK for a table of the parameter's types.

nFlags
The flags that specify the type of border to be drawn. See DrawEdge in the Windows SDK for a table of the parameter's values. For diagonal lines, the BF_RECT flags specify the end point of the vector bounded by the rectangle parameter.

Return Value

Nonzero if successful; otherwise 0.

CDC::DrawEscape

Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI).

int DrawEscape(
    int nEscape,  
    int nInputSize,  
    LPCSTR lpszInputData);

Parameters

nEscape
Specifies the escape function to be performed.

nInputSize
Specifies the number of bytes of data pointed to by the lpszInputData parameter.

lpszInputData
Points to the input structure required for the specified escape.

Return Value

Specifies the outcome of the function. Greater than zero if successful, except for the QUERYESCSUPPORT draw escape, which checks for implementation only; or zero if the escape is not implemented; or less than zero if an error occurred.

Remarks

When an application calls DrawEscape, the data identified by nInputSize and lpszInputData is passed directly to the specified display driver.

CDC::DrawFocusRect

Draws a rectangle in the style used to indicate that the rectangle has the focus.

void DrawFocusRect(LPCRECT lpRect);

Parameters

lpRect
Points to a RECT structure or a CRect object that specifies the logical coordinates of the rectangle to be drawn.

Remarks

Since this is a Boolean XOR function, calling this function a second time with the same rectangle removes the rectangle from the display. The rectangle drawn by this function cannot be scrolled. To scroll an area containing a rectangle drawn by this function, first call DrawFocusRect to remove the rectangle from the display, then scroll the area, and then call DrawFocusRect again to draw the rectangle in the new position.

Warning

DrawFocusRect works only in MM_TEXT mode. In other modes, this function does not draw the focus rectangle correctly, but it does not return error values.

CDC::DrawFrameControl

Call this member function to draw a frame control of the specified type and style.

BOOL DrawFrameControl(
    LPRECT lpRect,  
    UINT nType,  
    UINT nState);

Parameters

lpRect
A pointer to a RECT structure that contains the logical coordinates of the rectangle.

nType
Specifies the type of frame control to draw. See the uType parameter in DrawFrameControl in the Windows SDK for a list of this parameter's possible values.

nState
Specifies the initial state of the frame control. Can be one or more of the values described for the uState parameter in DrawFrameControl in the Windows SDK. Use the nState value DFCS_ADJUSTRECT to adjust the bounding rectangle to exclude the surrounding edge of the push button.

Return Value

Nonzero if successful; otherwise 0.

Remarks

In several cases, nState depends on the nType parameter. The following list shows the relationship between the four nType values and nState:

  • DFC_BUTTON

    • DFCS_BUTTON3STATE Three-state button

    • DFCS_BUTTONCHECK Check box

    • DFCS_BUTTONPUSH Push button

    • DFCS_BUTTONRADIO Radio button

    • DFCS_BUTTONRADIOIMAGE Image for radio button (nonsquare needs image)

    • DFCS_BUTTONRADIOMASK Mask for radio button (nonsquare needs mask)

  • DFC_CAPTION

    • DFCS_CAPTIONCLOSE Close button

    • DFCS_CAPTIONHELP Help button

    • DFCS_CAPTIONMAX Maximize button

    • DFCS_CAPTIONMIN Minimize button

    • DFCS_CAPTIONRESTORE Restore button

  • DFC_MENU

    • DFCS_MENUARROW Submenu arrow

    • DFCS_MENUBULLET Bullet

    • DFCS_MENUCHECK Check mark

  • DFC_SCROLL

    • DFCS_SCROLLCOMBOBOX Combo box scroll bar

    • DFCS_SCROLLDOWN Down arrow of scroll bar

    • DFCS_SCROLLLEFT Left arrow of scroll bar

    • DFCS_SCROLLRIGHT Right arrow of scroll bar

    • DFCS_SCROLLSIZEGRIP Size grip in bottom-right corner of window

    • DFCS_SCROLLUP Up arrow of scroll bar

Example

This code draws the size gripper in the bottom-right corner of your window. It's appropriate for the OnPaint handler of a dialog box, which has no styles and normally doesn't contain other controls (like a status bar) that may give it a size gripper.

void CDCView::DrawFC(CDC* pDC)
{
   CRect rc;
   GetClientRect(&rc);

   rc.left = rc.right - ::GetSystemMetrics(SM_CXHSCROLL);
   rc.top = rc.bottom - ::GetSystemMetrics(SM_CYVSCROLL);

   pDC->DrawFrameControl(rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
}

CDC::DrawIcon

Draws an icon on the device represented by the current CDC object.

BOOL DrawIcon(
    int x,  
    int y,  
    HICON hIcon);

 
BOOL DrawIcon(
    POINT point,  
    HICON hIcon);

Parameters

x
Specifies the logical x-coordinate of the upper-left corner of the icon.

y
Specifies the logical y-coordinate of the upper-left corner of the icon.

hIcon
Identifies the handle of the icon to be drawn.

point
Specifies the logical x- and y-coordinates of the upper-left corner of the icon. You can pass a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the function completed successfully; otherwise 0.

Remarks

The function places the icon's upper-left corner at the location specified by x and y. The location is subject to the current mapping mode of the device context.

The icon resource must have been previously loaded by using the functions CWinApp::LoadIcon, CWinApp::LoadStandardIcon, or CWinApp::LoadOEMIcon. The MM_TEXT mapping mode must be selected prior to using this function.

Example

See the example for CWnd::IsIconic.

CDC::DrawState

Call this member function to display an image and apply a visual effect to indicate a state, such as a disabled or default state.

Note

For all nFlag states except DSS_NORMAL, the image is converted to monochrome before the visual effect is applied.

BOOL DrawState(
    CPoint pt,  
    CSize size,  
    HBITMAP hBitmap,  
    UINT nFlags,  
    HBRUSH hBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    CBitmap* pBitmap,  
    UINT nFlags,  
    CBrush* pBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    HICON hIcon,  
    UINT nFlags,  
    HBRUSH hBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    HICON hIcon,  
    UINT nFlags,  
    CBrush* pBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    LPCTSTR lpszText,  
    UINT nFlags,  
    BOOL bPrefixText = TRUE,  
    int nTextLen = 0,  
    HBRUSH hBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    LPCTSTR lpszText,  
    UINT nFlags,  
    BOOL bPrefixText = TRUE,  
    int nTextLen = 0,  
    CBrush* pBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    DRAWSTATEPROC lpDrawProc,  
    LPARAM lData,  
    UINT nFlags,  
    HBRUSH hBrush = NULL);

 
BOOL DrawState(
    CPoint pt,  
    CSize size,  
    DRAWSTATEPROC lpDrawProc,  
    LPARAM lData,  
    UINT nFlags,  
    CBrush* pBrush = NULL);

Parameters

pt
Specifies the location of the image.

size
Specifies the size of the image.

hBitmap
A handle to a bitmap.

nFlags
Flags that specify the image type and state. See DrawState in the Windows SDK for the possible nFlags types and states.

hBrush
A handle to a brush.

pBitmap
A pointer to a CBitmap object.

pBrush
A pointer to a CBrush object.

hIcon
A handle to an icon.

lpszText
A pointer to text.

bPrefixText
Text that may contain an accelerator mnemonic. The lData parameter specifies the address of the string, and the nTextLen parameter specifies the length. If nTextLen is 0, the string is assumed to be null-terminated.

nTextLen
Length of the text string pointed to by lpszText. If nTextLen is 0, the string is assumed to be null-terminated.

lpDrawProc
A pointer to a callback function used to render an image. This parameter is required if the image type in nFlags is DST_COMPLEX. It is optional and can be NULL if the image type is DST_TEXT. For all other image types, this parameter is ignored. For more information about the callback function, see the DrawStateProc function in the Windows SDK.

lData
Specifies information about the image. The meaning of this parameter depends on the image type.

Return Value

Nonzero if successful; otherwise 0.

CDC::DrawText

Call this member function to format text in the given rectangle. To specify additional formatting options, use CDC::DrawTextEx.

virtual int DrawText(
    LPCTSTR lpszString,  
    int nCount,  
    LPRECT lpRect,  
    UINT nFormat);

 
int DrawText(
    const CString& str,  
    LPRECT lpRect,  
    UINT nFormat);

Parameters

lpszString
Points to the string to be drawn. If nCount is –1, the string must be null-terminated.

nCount
Specifies the number of chars in the string. If nCount is –1, then lpszString is assumed to be a long pointer to a null-terminated string and DrawText computes the character count automatically.

lpRect
Points to a RECT structure or CRect object that contains the rectangle (in logical coordinates) in which the text is to be formatted.

str
A CString object that contains the specified characters to be drawn.

nFormat
Specifies the method of formatting the text. It can be any combination of the values described for the uFormat parameter in DrawText in the Windows SDK. (combine using the bitwise OR operator):

Note

Some uFormat flag combinations can cause the passed string to be modified. Using DT_MODIFYSTRING with either DT_END_ELLIPSIS or DT_PATH_ELLIPSIS may cause the string to be modified, causing an assertion in the CString override. The values DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX cannot be used with the DT_TABSTOP value.

Return Value

The height of the text if the function is successful.

Remarks

It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by nFormat.

This member function uses the device context's selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawText clips the text so that the text does not appear outside the given rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is given.

If the selected font is too large for the specified rectangle, the DrawText member function does not attempt to substitute a smaller font.

If the DT_CALCRECT flag is specified, the rectangle specified by lpRect will be updated to reflect the width and height needed to draw the text.

If the TA_UPDATECP text-alignment flag has been set (see CDC::SetTextAlign), DrawText will display text starting at the current position, rather than at the left of the given rectangle. DrawText will not wrap text when the TA_UPDATECP flag has been set (that is, the DT_WORDBREAK flag will have no effect).

The text color may be set by CDC::SetTextColor.

CDC::DrawTextEx

Formats text in the given rectangle.

virtual int DrawTextEx(
    LPTSTR lpszString,  
    int nCount,  
    LPRECT lpRect,  
    UINT nFormat,
    LPDRAWTEXTPARAMS lpDTParams);

 
int DrawTextEx(
    const CString& str,  
    LPRECT lpRect,  
    UINT nFormat,
    LPDRAWTEXTPARAMS lpDTParams);

Parameters

lpszString
Points to the string to be drawn. If nCount is –1, the string must be null terminated.

nCount
Specifies the number of chars in the string. If nCount is –1, then lpszString is assumed to be a long pointer to a null-terminated string and DrawText computes the character count automatically.

lpRect
Points to a RECT structure or CRect object that contains the rectangle (in logical coordinates) in which the text is to be formatted.

str
A CString object that contains the specified characters to be drawn.

nFormat
Specifies the method of formatting the text. It can be any combination of the values described for the uFormat parameter in DrawText in the Windows SDK. (Combine using the bitwise OR operator):

Note

Some uFormat flag combinations can cause the passed string to be modified. Using DT_MODIFYSTRING with either DT_END_ELLIPSIS or DT_PATH_ELLIPSIS may cause the string to be modified, causing an assertion in the CString override. The values DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX cannot be used with the DT_TABSTOP value.

lpDTParams
Pointer to a DRAWTEXTPARAMS structure that specifies additional formatting options. This parameter can be NULL.

Remarks

It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by nFormat and lpDTParams. For more information, see CDC::DrawText and DrawTextEx in the Windows SDK.

The text color may be set by CDC::SetTextColor.

CDC::Ellipse

Draws an ellipse.

BOOL Ellipse(
    int x1,  
    int y1,  
    int x2,  
    int y2);  
  
BOOL Ellipse(LPCRECT lpRect);

Parameters

x1
Specifies the logical x-coordinate of the upper-left corner of the ellipse's bounding rectangle.

y1
Specifies the logical y-coordinate of the upper-left corner of the ellipse's bounding rectangle.

x2
Specifies the logical x-coordinate of the lower-right corner of the ellipse's bounding rectangle.

y2
Specifies the logical y-coordinate of the lower-right corner of the ellipse's bounding rectangle.

lpRect
Specifies the ellipse's bounding rectangle. You can also pass a CRect object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The center of the ellipse is the center of the bounding rectangle specified by x1, y1, x2, and y2, or lpRect. The ellipse is drawn with the current pen, and its interior is filled with the current brush.

The figure drawn by this function extends up to, but does not include, the right and bottom coordinates. This means that the height of the figure is y2y1 and the width of the figure is x2x1.

If either the width or the height of the bounding rectangle is 0, no ellipse is drawn.

CDC::EndDoc

Ends a print job started by a call to the StartDoc member function.

int EndDoc();

Return Value

Greater than or equal to 0 if the function is successful, or a negative value if an error occurred.

Remarks

This member function replaces the ENDDOC printer escape, and should be called immediately after finishing a successful print job.

If an application encounters a printing error or a canceled print operation, it must not attempt to terminate the operation by using either EndDoc or AbortDoc. GDI automatically terminates the operation before returning the error value.

This function should not be used inside metafiles.

Example

See the example for CDC::StartDoc.

CDC::EndPage

Informs the device that the application has finished writing to a page.

int EndPage();

Return Value

Greater than or equal to 0 if the function is successful, or a negative value if an error occurred.

Remarks

This member function is typically used to direct the device driver to advance to a new page.

This member function replaces the NEWFRAME printer escape. Unlike NEWFRAME, this function is always called after printing a page.

Example

See the example for CDC::StartDoc.

CDC::EndPath

Closes a path bracket and selects the path defined by the bracket into the device context.

BOOL EndPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Example

See the example for CDC::BeginPath.

CDC::EnumObjects

Enumerates the pens and brushes available in a device context.

int EnumObjects(
    int nObjectType,  
    int (CALLBACK* lpfn)(
    LPVOID,
    LPARAM),  
    LPARAM lpData);

Parameters

nObjectType
Specifies the object type. It can have the values OBJ_BRUSH or OBJ_PEN.

lpfn
Is the procedure-instance address of the application-supplied callback function. See the "Remarks" section below.

lpData
Points to the application-supplied data. The data is passed to the callback function along with the object information.

Return Value

Specifies the last value returned by the callback function. Its meaning is user-defined.

Remarks

For each object of a given type, the callback function that you pass is called with the information for that object. The system calls the callback function until there are no more objects or the callback function returns 0.

Note that new features of Microsoft Visual C++ let you use an ordinary function as the function passed to EnumObjects. The address passed to EnumObjects is a pointer to a function exported with EXPORT and with the Pascal calling convention. In protect-mode applications, you do not have to create this function with the Windows MakeProcInstance function or free the function after use with the FreeProcInstance Windows function.

You also do not have to export the function name in an EXPORTS statement in your application's module-definition file. You can instead use the EXPORT function modifier, as in

int CALLBACK EXPORT AFunction (LPSTR, LPSTR);

to cause the compiler to emit the proper export record for export by name without aliasing. This works for most needs. For some special cases, such as exporting a function by ordinal or aliasing the export, you still need to use an EXPORTS statement in a module-definition file.

For compiling Microsoft Foundation programs, you will normally use the /GA and /GEs compiler options. The /Gw compiler option is not used with the Microsoft Foundation classes. (If you do use the Windows function MakeProcInstance, you will need to explicitly cast the returned function pointer from FARPROC to the type needed in this API.) Callback registration interfaces are now type-safe (you must pass in a function pointer that points to the right kind of function for the specific callback).

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions.

Example

// print some info about a pen we're ready to enumerate
BOOL CALLBACK EnumObjectHandler(LPVOID lpLogObject, LPARAM /* lpData */)
{
   LOGPEN* pPen = (LOGPEN*) lpLogObject;
   
   switch (pPen->lopnStyle)
   {
   case PS_SOLID:
      TRACE0("PS_SOLID:      ");
      break;
   case PS_DASH:
      TRACE0("PS_DASH:       ");
      break;
   case PS_DOT:
      TRACE0("PS_DOT:        ");
      break;
   case PS_DASHDOT:
      TRACE0("PS_DASHDOT:    ");
      break;
   case PS_DASHDOTDOT:
      TRACE0("PS_DASHDOTDOT: ");
      break;
   case PS_NULL:
      TRACE0("PS_NULL:       ");
      break;
   case PS_INSIDEFRAME:
      TRACE0("PS_INSIDEFRAME:");
      break;
   default:
      TRACE0("unk style:");
   }

   TRACE2("Color: 0x%8.8X, Width: %d\n", pPen->lopnColor, pPen->lopnWidth);
   return TRUE;
}

// get the default printer and enumerate the pens it has
void CDCView::OnEnumPens()
{
   CPrintDialog dlg(FALSE);
   dlg.GetDefaults();
   HDC hdc = dlg.GetPrinterDC();

   if (hdc != NULL)
   {
      CDC dc;
      dc.Attach(hdc);
      VERIFY(dc.EnumObjects(OBJ_PEN, EnumObjectHandler, 0));
   }
}

CDC::Escape

This member function is practically obsolete for Win32 programming.

virtual int Escape(
    int nEscape,  
    int nCount,  
    LPCSTR lpszInData,  
    LPVOID lpOutData);

 
int Escape(
    int nEscape,  
    int nInputSize,  
    LPCSTR lpszInputData,  
    int nOutputSize,  
    LPSTR lpszOutputData);

Parameters

nEscape
Specifies the escape function to be performed.

For a complete list of escape functions, see Escape in the Windows SDK.

nCount
Specifies the number of bytes of data pointed to by lpszInData.

lpszInData
Points to the input data structure required for this escape.

lpOutData
Points to the structure that is to receive output from this escape. The lpOutData parameter is NULL if no data is returned.

nInputSize
Specifies the number of bytes of data pointed to by the lpszInputData parameter.

lpszInputData
Points to the input structure required for the specified escape.

nOutputSize
Specifies the number of bytes of data pointed to by the lpszOutputData parameter.

lpszOutputData
Points to the structure that receives output from this escape. This parameter should be NULL if no data is returned.

Return Value

A positive value is returned if the function is successful, except for the QUERYESCSUPPORT escape, which only checks for implementation. Zero is returned if the escape is not implemented. A negative value is returned if an error occurred. The following are common error values:

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User ended the job through the Print Manager.

Remarks

Of the original printer escapes, only QUERYESCSUPPORT is supported for Win32 applications. All other printer escapes are obsolete and are supported only for compatibility with 16-bit applications.

For Win32 programming, CDC now provides six member functions that supersede their corresponding printer escapes:

  • CDC::AbortDoc

  • CDC::EndDoc

  • CDC::EndPage

  • CDC::SetAbortProc

  • CDC::StartDoc

  • CDC::StartPage

In addition, CDC::GetDeviceCaps supports Win32 indexes that supersede other printer escapes. See GetDeviceCaps in the Windows SDK for more information.

This member function allows applications to access facilities of a particular device that are not directly available through GDI.

Use the first version if your application uses predefined escape values. Use the second version if your application defines private escape values. See ExtEscape in the Windows SDK for more information about the second version.

CDC::ExcludeClipRect

Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.

int ExcludeClipRect(
    int x1,  
    int y1,  
    int x2,  
    int y2);  
  
int ExcludeClipRect(LPCRECT lpRect);

Parameters

x1
Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y1
Specifies the logical y-coordinate of the upper-left corner of the rectangle.

x2
Specifies the logical x-coordinate of the lower-right corner of the rectangle.

y2
Specifies the logical y-coordinate of the lower-right corner of the rectangle.

lpRect
Specifies the rectangle. Can also be a CRect object.

Return Value

Specifies the new clipping region's type. It can be any of the following values:

  • COMPLEXREGION The region has overlapping borders.

  • ERROR No region was created.

  • NULLREGION The region is empty.

  • SIMPLEREGION The region has no overlapping borders.

Remarks

The width of the rectangle, specified by the absolute value of x2x1, must not exceed 32,767 units. This limit applies to the height of the rectangle as well.

CDC::ExcludeUpdateRgn

Prevents drawing within invalid areas of a window by excluding an updated region in the window from the clipping region associated with the CDC object.

int ExcludeUpdateRgn(CWnd* pWnd);

Parameters

pWnd
Points to the window object whose window is being updated.

Return Value

The type of excluded region. It can be any one of the following values:

  • COMPLEXREGION The region has overlapping borders.

  • ERROR No region was created.

  • NULLREGION The region is empty.

  • SIMPLEREGION The region has no overlapping borders.

CDC::ExtFloodFill

Fills an area of the display surface with the current brush.

BOOL ExtFloodFill(
    int x,  
    int y,  
    COLORREF crColor,  
    UINT nFillType);

Parameters

x
Specifies the logical x-coordinate of the point where filling begins.

y
Specifies the logical y-coordinate of the point where filling begins.

crColor
Specifies the color of the boundary or of the area to be filled. The interpretation of crColor depends on the value of nFillType.

nFillType
Specifies the type of flood fill to be performed. It must be either of the following values:

  • FLOODFILLBORDER The fill area is bounded by the color specified by crColor. This style is identical to the filling performed by FloodFill.

  • FLOODFILLSURFACE The fill area is defined by the color specified by crColor. Filling continues outward in all directions as long as the color is encountered. This style is useful for filling areas with multicolored boundaries.

Return Value

Nonzero if the function is successful; otherwise 0 if the filling could not be completed, if the given point has the boundary color specified by crColor (if FLOODFILLBORDER was requested), if the given point does not have the color specified by crColor (if FLOODFILLSURFACE was requested), or if the point is outside the clipping region.

Remarks

This member function offers more flexibility than FloodFill because you can specify a fill type in nFillType.

If nFillType is set to FLOODFILLBORDER, the area is assumed to be completely bounded by the color specified by crColor. The function begins at the point specified by x and y and fills in all directions to the color boundary.

If nFillType is set to FLOODFILLSURFACE, the function begins at the point specified by x and y and continues in all directions, filling all adjacent areas containing the color specified by crColor.

Only memory-device contexts and devices that support raster-display technology support ExtFloodFill. For more information, see the GetDeviceCaps member function.

CDC::ExtTextOut

Call this member function to write a character string within a rectangular region using the currently selected font.

virtual BOOL ExtTextOut(
    int x,  
    int y,  
    UINT nOptions,  
    LPCRECT lpRect,  
    LPCTSTR lpszString,  
    UINT nCount,  
    LPINT lpDxWidths);

 
BOOL ExtTextOut(
    int x,  
    int y,  
    UINT nOptions,  
    LPCRECT lpRect,  
    const CString& str,  
    LPINT lpDxWidths);

Parameters

x
Specifies the logical x-coordinate of the character cell for the first character in the specified string.

y
Specifies the logical y-coordinate of the top of the character cell for the first character in the specified string.

nOptions
Specifies the rectangle type. This parameter can be one, both, or neither of the following values:

  • ETO_CLIPPED Specifies that text is clipped to the rectangle.

  • ETO_OPAQUE Specifies that the current background color fills the rectangle. (You can set and query the current background color with the SetBkColor and GetBkColor member functions.)

lpRect
Points to a RECT structure that determines the dimensions of the rectangle. This parameter can be NULL. You can also pass a CRect object for this parameter.

lpszString
Points to the specified character string to be drawn. You can also pass a CString object for this parameter.

nCount
Specifies the number of characters in the string.

lpDxWidths
Points to an array of values that indicate the distance between origins of adjacent character cells. For instance, lpDxWidths[ i] logical units will separate the origins of character cell i and character cell i + 1. If lpDxWidths is NULL, ExtTextOut uses the default spacing between characters.

str
A CString object that contains the specified characters to be drawn.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The rectangular region can be opaque (filled with the current background color), and it can be a clipping region.

If nOptions is 0 and lpRect is NULL, the function writes text to the device context without using a rectangular region. By default, the current position is not used or updated by the function. If an application needs to update the current position when it calls ExtTextOut, the application can call the CDC member function SetTextAlign with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores x and y on subsequent calls to ExtTextOut and uses the current position instead. When an application uses TA_UPDATECP to update the current position, ExtTextOut sets the current position either to the end of the previous line of text or to the position specified by the last element of the array pointed to by lpDxWidths, whichever is greater.

CDC::FillPath

Closes any open figures in the current path and fills the path's interior by using the current brush and polygon-filling mode.

BOOL FillPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

After its interior is filled, the path is discarded from the device context.

CDC::FillRect

Call this member function to fill a given rectangle using the specified brush.

void FillRect(
    LPCRECT lpRect,  
    CBrush* pBrush);

Parameters

lpRect
Points to a RECT structure that contains the logical coordinates of the rectangle to be filled. You can also pass a CRect object for this parameter.

pBrush
Identifies the brush used to fill the rectangle.

Remarks

The function fills the complete rectangle, including the left and top borders, but it does not fill the right and bottom borders.

The brush needs to either be created using the CBrush member functions CreateHatchBrush, CreatePatternBrush, and CreateSolidBrush, or retrieved by the GetStockObject Windows function.

When filling the specified rectangle, FillRect does not include the rectangle's right and bottom sides. GDI fills a rectangle up to, but does not include, the right column and bottom row, regardless of the current mapping mode. FillRect compares the values of the top, bottom, left, and right members of the specified rectangle. If bottom is less than or equal to top, or if right is less than or equal to left, the rectangle is not drawn.

FillRect is similar to CDC::FillSolidRect; however, FillRect takes a brush and therefore can be used to fill a rectangle with a solid color, a dithered color, hatched brushes, or a pattern. FillSolidRect uses only solid colors (indicated by a COLORREF parameter). FillRect usually is slower than FillSolidRect.

CDC::FillRgn

Fills the region specified by pRgn with the brush specified by pBrush.

BOOL FillRgn(
    CRgn* pRgn,  
    CBrush* pBrush);

Parameters

pRgn
A pointer to the region to be filled. The coordinates for the given region are specified in logical units.

pBrush
Identifies the brush to be used to fill the region.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The brush must either be created using the CBrush member functions CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, or be retrieved by GetStockObject.

Example

See the example for CRgn::CreateRoundRectRgn.

CDC::FillSolidRect

Call this member function to fill the given rectangle with the specified solid color.

void FillSolidRect(
    LPCRECT lpRect,  
    COLORREF clr);

 
void FillSolidRect(
    int x,  
    int y,  
    int cx,  
    int cy,  
    COLORREF clr);

Parameters

lpRect
Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT data structure or a CRect object for this parameter.

clr Specifies the color to be used to fill the rectangle.

x
Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y
Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

cx
Specifies the width of the rectangle.

cy
Specifies the height of the rectangle.

Remarks

FillSolidRect is very similar to CDC::FillRect; however, FillSolidRect uses only solid colors (indicated by the COLORREF parameter), while FillRect takes a brush and therefore can be used to fill a rectangle with a solid color, a dithered color, hatched brushes, or a pattern. FillSolidRect usually is faster than FillRect.

Note

When you call FillSolidRect, the background color, which was previously set using SetBkColor, is set to the color indicated by clr.

CDC::FlattenPath

Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines.

BOOL FlattenPath();

Return Value

Nonzero if the function is successful; otherwise 0.

CDC::FloodFill

Fills an area of the display surface with the current brush.

BOOL FloodFill(
    int x,  
    int y,  
    COLORREF crColor);

Parameters

x
Specifies the logical x-coordinate of the point where filling begins.

y
Specifies the logical y-coordinate of the point where filling begins.

crColor
Specifies the color of the boundary.

Return Value

Nonzero if the function is successful; otherwise 0 is returned if the filling could not be completed, the given point has the boundary color specified by crColor, or the point is outside the clipping region.

Remarks

The area is assumed to be bounded as specified by crColor. The FloodFill function begins at the point specified by x and y and continues in all directions to the color boundary.

Only memory-device contexts and devices that support raster-display technology support the FloodFill member function. For information about RC_BITBLT capability, see the GetDeviceCaps member function.

The ExtFloodFill function provides similar capability but greater flexibility.

CDC::FrameRect

Draws a border around the rectangle specified by lpRect.

void FrameRect(
    LPCRECT lpRect,  
    CBrush* pBrush);

Parameters

lpRect
Points to a RECT structure or CRect object that contains the logical coordinates of the upper-left and lower-right corners of the rectangle. You can also pass a CRect object for this parameter.

pBrush
Identifies the brush to be used for framing the rectangle.

Remarks

The function uses the given brush to draw the border. The width and height of the border is always 1 logical unit.

If the rectangle's bottom coordinate is less than or equal to top, or if right is less than or equal to left, the rectangle is not drawn.

The border drawn by FrameRect is in the same position as a border drawn by the Rectangle member function using the same coordinates (if Rectangle uses a pen that is 1 logical unit wide). The interior of the rectangle is not filled by FrameRect.

CDC::FrameRgn

Draws a border around the region specified by pRgn using the brush specified by pBrush.

BOOL FrameRgn(
    CRgn* pRgn,  
    CBrush* pBrush,  
    int nWidth,  
    int nHeight);

Parameters

pRgn
Points to the CRgn object that identifies the region to be enclosed in a border. The coordinates for the given region are specified in logical units.

pBrush
Points to the CBrush object that identifies the brush to be used to draw the border.

nWidth
Specifies the width of the border in vertical brush strokes in device units.

nHeight
Specifies the height of the border in horizontal brush strokes in device units.

Return Value

Nonzero if the function is successful; otherwise 0.

Example

See the example for CRgn::CombineRgn.

CDC::FromHandle

Returns a pointer to a CDC object when given a handle to a device context.

static CDC* PASCAL FromHandle(HDC hDC);

Parameters

hDC
Contains a handle to a Windows device context.

Return Value

The pointer may be temporary and should not be stored beyond immediate use.

Remarks

If a CDC object is not attached to the handle, a temporary CDC object is created and attached.

Example

See the example for CPrintDialog::GetPrinterDC.

CDC::GetArcDirection

Returns the current arc direction for the device context.

int GetArcDirection() const;  

Return Value

Specifies the current arc direction, if successful. Following are the valid return values:

  • AD_COUNTERCLOCKWISE Arcs and rectangles drawn counterclockwise.

  • AD_CLOCKWISE Arcs and rectangles drawn clockwise.

If an error occurs, the return value is zero.

Remarks

Arc and rectangle functions use the arc direction.

CDC::GetAspectRatioFilter

Retrieves the setting for the current aspect-ratio filter.

CSize GetAspectRatioFilter() const;  

Return Value

A CSize object representing the aspect ratio used by the current aspect ratio filter.

Remarks

The aspect ratio is the ratio formed by a device's pixel width and height. Information about a device's aspect ratio is used in the creation, selection, and display of fonts. Windows provides a special filter, the aspect-ratio filter, to select fonts designed for a particular aspect ratio from all of the available fonts. The filter uses the aspect ratio specified by the SetMapperFlags member function.

CDC::GetBkColor

Returns the current background color.

COLORREF GetBkColor() const;  

Return Value

An RGB color value.

Remarks

If the background mode is OPAQUE, the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. The system also uses the background color when converting bitmaps between color and monochrome device contexts.

CDC::GetBkMode

Returns the background mode.

int GetBkMode() const;  

Return Value

The current background mode, which can be OPAQUE or TRANSPARENT.

Remarks

The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line.

CDC::GetBoundsRect

Returns the current accumulated bounding rectangle for the specified device context.

UINT GetBoundsRect(
    LPRECT lpRectBounds,  
    UINT flags);

Parameters

lpRectBounds
Points to a buffer that will receive the current bounding rectangle. The rectangle is returned in logical coordinates.

flags
Specifies whether the bounding rectangle is to be cleared after it is returned. This parameter should be zero or set to the following value:

  • DCB_RESET Forces the bounding rectangle to be cleared after it is returned.

Return Value

Specifies the current state of the bounding rectangle if the function is successful. It can be a combination of the following values:

  • DCB_ACCUMULATE Bounding rectangle accumulation is occurring.

  • DCB_RESET Bounding rectangle is empty.

  • DCB_SET Bounding rectangle is not empty.

  • DCB_ENABLE Bounding accumulation is on.

  • DCB_DISABLE Bounding accumulation is off.

CDC::GetBrushOrg

Retrieves the origin (in device units) of the brush currently selected for the device context.

CPoint GetBrushOrg() const;  

Return Value

The current origin of the brush (in device units) as a CPoint object.

Remarks

The initial brush origin is at (0,0) of the client area. The return value specifies this point in device units relative to the origin of the desktop window.

CDC::GetCharacterPlacement

Retrieves various types of information on a character string.

DWORD GetCharacterPlacement(
    LPCTSTR lpString,  
    int nCount,  
    int nMaxExtent,  
    LPGCP_RESULTS lpResults,  
    DWORD dwFlags) const;  
  
DWORD GetCharacterPlacement(
    CString& str,  
    int nMaxExtent,  
    LPGCP_RESULTS lpResults,  
    DWORD dwFlags) const;  

Parameters

lpString
A pointer to the character string to process.

nCount
Specifies the length of the string. For the ANSI version, it is a BYTE count and for the Unicode function it is a WORD count. For more information, see GetCharacterPlacement.

nMaxExtent
Specifies the maximum extent (in logical units) to which the string is processed. Characters that, if processed, would exceed this extent are ignored. Computations for any required ordering or glyph arrays apply only to the included characters. This parameter is used only if the GCP_MAXEXTENT value is specified in the dwFlags parameter. As the function processes the input string, each character and its extent is added to the output, extent, and other arrays only if the total extent has not yet exceeded the maximum. Once the limit is reached, processing will stop.

lpResults
Pointer to a GCP_Results structure that receives the results of the function.

dwFlags
Specifies how to process the string into the required arrays. This parameter can be one or more of the values listed in the dwFlags section of the GetCharacterPlacement topic.

str
A pointer to a CString object to process.

Return Value

If the function succeeds, the return value is the width and height of the string in logical units.

If the function fails, the return value is zero.

Remarks

This member function emulates the functionality of the function GetCharacterPlacement, as described in the Windows SDK.

CDC::GetCharABCWidths

Retrieves the widths of consecutive characters in a specified range from the current TrueType font.

BOOL GetCharABCWidths(
    UINT nFirstChar,  
    UINT nLastChar,  
    LPABC lpabc) const;  
  
BOOL GetCharABCWidths(
    UINT nFirstChar,  
    UINT nLastChar,  
    LPABCFLOAT lpABCF) const;  

Parameters

nFirstChar
Specifies the first character in the range of characters from the current font for which character widths are returned.

nLastChar
Specifies the last character in the range of characters from the current font for which character widths are returned.

lpabc
Points to an array of ABC structures that receive the character widths when the function returns. This array must contain at least as many ABC structures as there are characters in the range specified by the nFirstChar and nLastChar parameters.

lpABCF
Points to an application-supplied buffer with an array of ABCFLOAT structures to receive the character widths when the function returns. The widths returned by this function are in the IEEE floating-point format.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The widths are returned in logical units. This function succeeds only with TrueType fonts.

The TrueType rasterizer provides "ABC" character spacing after a specific point size has been selected. "A" spacing is the distance that is added to the current position before placing the glyph. "B" spacing is the width of the black part of the glyph. "C" spacing is added to the current position to account for the white space to the right of the glyph. The total advanced width is given by A + B + C.

When the GetCharABCWidths member function retrieves negative "A" or "C" widths for a character, that character includes underhangs or overhangs.

To convert the ABC widths to font design units, an application should create a font whose height (as specified in the lfHeight member of the LOGFONT structure) is equal to the value stored in the ntmSizeEM member of the NEWTEXTMETRIC structure. (The value of the ntmSizeEM member can be retrieved by calling the EnumFontFamilies Windows function.)

The ABC widths of the default character are used for characters that are outside the range of the currently selected font.

To retrieve the widths of characters in non-TrueType fonts, applications should use the GetCharWidth Windows function.

CDC::GetCharABCWidthsI

Retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font.

BOOL GetCharABCWidthsI(
    UINT giFirst,  
    UINT cgi,  
    LPWORD pgi,  
    LPABC lpabc) const;  

Parameters

giFirst
Specifies the first glyph index in the group of consecutive glyph indices from the current font. This parameter is only used if the pgi parameter is NULL.

cgi
Specifies the number of glyph indices.

pgi
A pointer to an array containing glyph indices. If the value is NULL, the giFirst parameter is used instead. The cgi parameter specifies the number of glyph indices in this array.

lpabc
Pointer to an array of ABC structures receiving the character widths. This array must contain at least as many ABC structures as there are glyph indices specified by the cgi parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This member function emulates the functionality of the function GetCharABCWidthsI, as described in the Windows SDK.

CDC::GetCharWidth

Retrieves the widths of individual characters in a consecutive group of characters from the current font, using m_hAttribDC, the input device context.

BOOL GetCharWidth(
    UINT nFirstChar,  
    UINT nLastChar,  
    LPINT lpBuffer) const;  
  
BOOL GetCharWidth(
    UINT nFirstChar,  
    UINT nLastChar,  
    float* lpFloatBuffer) const;  

Parameters

nFirstChar
Specifies the first character in a consecutive group of characters in the current font.

nLastChar
Specifies the last character in a consecutive group of characters in the current font.

lpBuffer
Points to a buffer that will receive the width values for a consecutive group of characters in the current font.

lpFloatBuffer
Points to a buffer to receive the character widths. The returned widths are in the 32-bit IEEE floating-point format. (The widths are measured along the base line of the characters.)

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

For example, if nFirstChar identifies the letter 'a' and nLastChar identifies the letter 'z', the function retrieves the widths of all lowercase characters.

The function stores the values in the buffer pointed to by lpBuffer. This buffer must be large enough to hold all of the widths. That is, there must be at least 26 entries in the example given.

If a character in the consecutive group of characters does not exist in a particular font, it will be assigned the width value of the default character.

CDC::GetCharWidthI

Retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font.

BOOL GetCharWidthI(
    UINT giFirst,  
    UINT cgi,  
    LPWORD pgi,  
    LPINT lpBuffer) const;  

Parameters

giFirst
Specifies the first glyph index in the group of consecutive glyph indices from the current font. This parameter is only used if the pgi parameter is NULL.

cgi
Specifies the number of glyph indices.

pgi
A pointer to an array containing glyph indices. If the value is NULL, the giFirst parameter is used instead. The cgi parameter specifies the number of glyph indices in this array.

lpBuffer
A pointer to a buffer that receives the widths.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This member function emulates the functionality of the function GetCharWidthI, as described in the Windows SDK.

CDC::GetClipBox

Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary.

virtual int GetClipBox(LPRECT lpRect) const;  

Parameters

lpRect
Points to the RECT structure or CRect object that is to receive the rectangle dimensions.

Return Value

The clipping region's type. It can be any of the following values:

  • COMPLEXREGION Clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION Clipping region is empty.

  • SIMPLEREGION Clipping region has no overlapping borders.

Remarks

The dimensions are copied to the buffer pointed to by lpRect.

CDC::GetColorAdjustment

Retrieves the color adjustment values for the device context.

BOOL GetColorAdjustment(LPCOLORADJUSTMENT lpColorAdjust) const;  

Parameters

lpColorAdjust
Points to a COLORADJUSTMENT data structure to receive the color adjustment values.

Return Value

Nonzero if the function is successful; otherwise 0.

CDC::GetCurrentBitmap

Returns a pointer to the currently selected CBitmap object.

CBitmap* GetCurrentBitmap() const;  

Return Value

Pointer to a CBitmap object, if successful; otherwise NULL.

Remarks

This member function may return temporary objects.

CDC::GetCurrentBrush

Returns a pointer to the currently selected CBrush object.

CBrush* GetCurrentBrush() const;  

Return Value

Pointer to a CBrush object, if successful; otherwise NULL.

Remarks

This member function may return temporary objects.

CDC::GetCurrentFont

Returns a pointer to the currently selected CFont object.

CFont* GetCurrentFont() const;  

Return Value

Pointer to a CFont object, if successful; otherwise NULL.

Remarks

This member function may return temporary objects.

CDC::GetCurrentPalette

Returns a pointer to the currently selected CPalette object.

CPalette* GetCurrentPalette() const;  

Return Value

Pointer to a CPalette object, if successful; otherwise NULL.

Remarks

This member function may return temporary objects.

CDC::GetCurrentPen

Returns a pointer to the currently selected CPen object.

CPen* GetCurrentPen() const;  

Return Value

Pointer to a CPen object, if successful; otherwise NULL.

Remarks

This member function may return temporary objects.

CDC::GetCurrentPosition

Retrieves the current position (in logical coordinates).

CPoint GetCurrentPosition() const;  

Return Value

The current position as a CPoint object.

Remarks

The current position can be set with the MoveTo member function.

CDC::GetDCBrushColor

Retrieves the current brush color.

COLORREF GetDCBrushColor() const;  

Return Value

If the function succeeds, the return value is the COLORREF value for the current brush color.

If the function fails, the return value is CLR_INVALID.

Remarks

This member function emulates the functionality of the function GetDCBrushColor, as described in the Windows SDK.

CDC::GetDCPenColor

Retrieves the current pen color.

COLORREF GetDCPenColor() const;  

Return Value

If the function succeeds, the return value is the COLORREF value for the current pen color.

If the function fails, the return value is CLR_INVALID.

Remarks

This member function utilizes the Win32 function GetDCPenColor, as described in the Windows SDK.

CDC::GetDeviceCaps

Retrieves a wide range of device-specific information about the display device.

int GetDeviceCaps(int nIndex) const;  

Parameters

nIndex
Specifies the type of information to return. See GetDeviceCaps in the Windows SDK for a list of values.

Return Value

The value of the requested capability if the function is successful.

Example

See the example for CPrintDialog::GetDefaults.

CDC::GetFontData

Retrieves font-metric information from a scalable font file.

DWORD GetFontData(
    DWORD dwTable,  
    DWORD dwOffset,  
    LPVOID lpData,  
    DWORD cbData) const;  

Parameters

dwTable
Specifies the name of the metric table to be returned. This parameter can be one of the metric tables documented in the TrueType Font Files specification published by Microsoft Corporation. If this parameter is 0, the information is retrieved starting at the beginning of the font file.

dwOffset
Specifies the offset from the beginning of the table at which to begin retrieving information. If this parameter is 0, the information is retrieved starting at the beginning of the table specified by the dwTable parameter. If this value is greater than or equal to the size of the table, GetFontData returns 0.

lpData
Points to a buffer that will receive the font information. If this value is NULL, the function returns the size of the buffer required for the font data specified in the dwTable parameter.

cbData
Specifies the length, in bytes, of the information to be retrieved. If this parameter is 0, GetFontData returns the size of the data specified in the dwTable parameter.

Return Value

Specifies the number of bytes returned in the buffer pointed to by lpData if the function is successful; otherwise –1.

Remarks

The information to retrieve is identified by specifying an offset into the font file and the length of the information to return.

An application can sometimes use the GetFontData member function to save a TrueType font with a document. To do this, the application determines whether the font can be embedded and then retrieves the entire font file, specifying 0 for the dwTable, dwOffset, and cbData parameters.

Applications can determine whether a font can be embedded by checking the otmfsType member of the OUTLINETEXTMETRIC structure. If bit 1 of otmfsType is set, embedding is not permitted for the font. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read only.

If an application attempts to use this function to retrieve information for a non-TrueType font, the GetFontData member function returns –1.

CDC::GetFontLanguageInfo

Returns information about the currently selected font for the specified display context.

DWORD GetFontLanguageInfo() const;  

Return Value

The return value identifies characteristics of the currently selected font. For a complete listing of possible values, see GetFontLanguageInfo.

Remarks

This member function emulates the functionality of the function GetFontLanguageInfo, as described in the Windows SDK.

CDC::GetGlyphOutline

Retrieves the outline curve or bitmap for an outline character in the current font.

DWORD GetGlyphOutline(
    UINT nChar,  
    UINT nFormat,  
    LPGLYPHMETRICS lpgm,  
    DWORD cbBuffer,  
    LPVOID lpBuffer,  
    const MAT2* lpmat2) const;  

Parameters

nChar
Specifies the character for which information is to be returned.

nFormat
Specifies the format in which the function is to return information. It can be one of the following values, or 0:

Value Meaning
GGO_BITMAP Returns the glyph bitmap. When the function returns, the buffer pointed to by lpBuffer contains a 1-bit-per-pixel bitmap whose rows start on doubleword boundaries.
GGO_NATIVE Returns the curve data points in the rasterizer's native format, using device units. When this value is specified, any transformation specified in lpmat2 is ignored.

When the value of nFormat is 0, the function fills in a GLYPHMETRICS structure but does not return glyph-outline data.

lpgm
Points to a GLYPHMETRICS structure that describes the placement of the glyph in the character cell.

cbBuffer
Specifies the size of the buffer into which the function copies information about the outline character. If this value is 0 and the nFormat parameter is either the GGO_BITMAP or GGO_NATIVE values, the function returns the required size of the buffer.

lpBuffer
Points to a buffer into which the function copies information about the outline character. If nFormat specifies the GGO_NATIVE value, the information is copied in the form of TTPOLYGONHEADER and TTPOLYCURVE structures. If this value is NULL and nFormat is either the GGO_BITMAP or GGO_NATIVE value, the function returns the required size of the buffer.

lpmat2
Points to a MAT2 structure that contains a transformation matrix for the character. This parameter cannot be NULL, even when the GGO_NATIVE value is specified for nFormat.

Return Value

The size, in bytes, of the buffer required for the retrieved information if cbBuffer is 0 or lpBuffer is NULL. Otherwise, it is a positive value if the function is successful, or –1 if there is an error.

Remarks

An application can rotate characters retrieved in bitmap format by specifying a 2-by-2 transformation matrix in the structure pointed to by lpmat2.

A glyph outline is returned as a series of contours. Each contour is defined by a TTPOLYGONHEADER structure followed by as many TTPOLYCURVE structures as are required to describe it. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point given by the pfxStart member of the TTPOLYGONHEADER structure is the point at which the outline for a contour begins. The TTPOLYCURVE structures that follow can be either polyline records or spline records. Polyline records are a series of points; lines drawn between the points describe the outline of the character. Spline records represent the quadratic curves used by TrueType (that is, quadratic b-splines).

CDC::GetGraphicsMode

Retrieves the current graphics mode for the specified device context.

int GetGraphicsMode() const;  

Return Value

Returns the current graphics mode on success. For a list of the values that this method can return, see GetGraphicsMode.

Returns 0 on failure.

To get extended error information, call GetLastError.

Remarks

This method wraps the Windows GDI function GetGraphicsMode.

CDC::GetHalftoneBrush

Call this member function to retrieve a halftone brush.

static CBrush* PASCAL GetHalftoneBrush();

Return Value

A pointer to a CBrush object if successful; otherwise NULL.

Remarks

A halftone brush shows pixels that are alternately foreground and background colors to create a dithered pattern. The following is an example of a dithered pattern created by a halftone brush.

Detail of a dithered pen stroke

CDC::GetKerningPairs

Retrieves the character kerning pairs for the font that is currently selected in the specified device context.

int GetKerningPairs(
    int nPairs,  
    LPKERNINGPAIR lpkrnpair) const;  

Parameters

nPairs
Specifies the number of KERNINGPAIR structures pointed to by lpkrnpair. The function will not copy more kerning pairs than specified by nPairs.

lpkrnpair
Points to an array of KERNINGPAIR structures that receive the kerning pairs when the function returns. This array must contain at least as many structures as specified by nPairs. If this parameter is NULL, the function returns the total number of kerning pairs for the font.

Return Value

Specifies the number of kerning pairs retrieved or the total number of kerning pairs in the font, if the function is successful. Zero is returned if the function fails or there are no kerning pairs for the font.

CDC::GetLayout

Call this member function to determine the layout of the text and graphics for a device context, such as a printer or a metafile.

DWORD GetLayout() const;  

Return Value

If successful, the layout flags for the current device context. Otherwise, GDI_ERROR. For extended error information, call GetLastError. For a list of the layout flags, see CDC::SetLayout.

Remarks

The default layout is left to right.

CDC::GetMapMode

Retrieves the current mapping mode.

int GetMapMode() const;  

Return Value

The mapping mode.

Remarks

For a description of the mapping modes, see the SetMapMode member function.

Note

If you call SetLayout to change the DC to right-to-left layout, SetLayout automatically changes the mapping mode to MM_ISOTROPIC. Consequently, any subsequent call to GetMapMode will return MM_ISOTROPIC.

CDC::GetMiterLimit

Returns the miter limit for the device context.

float GetMiterLimit() const;  

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The miter limit is used when drawing geometric lines that have miter joins.

CDC::GetNearestColor

Returns the solid color that best matches a specified logical color.

COLORREF GetNearestColor(COLORREF crColor) const;  

Parameters

crColor
Specifies the color to be matched.

Return Value

An RGB (red, green, blue) color value that defines the solid color closest to the crColor value that the device can represent.

Remarks

The given device must be able to represent this color.

CDC::GetOutlineTextMetrics

Retrieves metric information for TrueType fonts.

UINT GetOutlineTextMetrics(
    UINT cbData,  
    LPOUTLINETEXTMETRIC lpotm) const;  

Parameters

lpotm
Points to an array of OUTLINETEXTMETRIC structures. If this parameter is NULL, the function returns the size of the buffer required for the retrieved metric data.

cbData
Specifies the size, in bytes, of the buffer to which information is returned.

lpotm
Points to an OUTLINETEXTMETRIC structure. If this parameter is NULL, the function returns the size of the buffer required for the retrieved metric information.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The OUTLINETEXTMETRIC structure contains most of the font metric information provided with the TrueType format, including a TEXTMETRIC structure. The last four members of the OUTLINETEXTMETRIC structure are pointers to strings. Applications should allocate space for these strings in addition to the space required for the other members. Because there is no system-imposed limit to the size of the strings, the simplest method for allocating memory is to retrieve the required size by specifying NULL for lpotm in the first call to the GetOutlineTextMetrics function.

CDC::GetOutputCharWidth

Uses the output device context, m_hDC, and retrieves the widths of individual characters in a consecutive group of characters from the current font.

BOOL GetOutputCharWidth(
    UINT nFirstChar,  
    UINT nLastChar,  
    LPINT lpBuffer) const;  

Parameters

nFirstChar
Specifies the first character in a consecutive group of characters in the current font.

nLastChar
Specifies the last character in a consecutive group of characters in the current font.

lpBuffer
Points to a buffer that will receive the width values for a consecutive group of characters in the current font.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

For example, if nFirstChar identifies the letter 'a' and nLastChar identifies the letter 'z', the function retrieves the widths of all lowercase characters.

The function stores the values in the buffer pointed to by lpBuffer. This buffer must be large enough to hold all of the widths; that is, there must be at least 26 entries in the example given.

If a character in the consecutive group of characters does not exist in a particular font, it will be assigned the width value of the default character.

CDC::GetOutputTabbedTextExtent

Call this member function to compute the width and height of a character string using m_hDC, the output device context.

CSize GetOutputTabbedTextExtent(
    LPCTSTR lpszString,  
    int nCount,  
    int nTabPositions,  
    LPINT lpnTabStopPositions) const;  
  
CSize GetOutputTabbedTextExtent(
    const CString& str,  
    int nTabPositions,  
    LPINT lpnTabStopPositions) const;  

Parameters

lpszString
Points to a character string to be measured. You can also pass a CString object for this parameter.

nCount
Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions
Specifies the number of tab-stop positions in the array pointed to by lpnTabStopPositions.

lpnTabStopPositions
Points to an array of integers containing the tab-stop positions in logical units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array. Back tabs are not allowed.

str
A CString object that contains the specified characters to be measured.

Return Value

The dimensions of the string (in logical units) in a CSize object.

Remarks

If the string contains one or more tab characters, the width of the string is based upon the tab stops specified by lpnTabStopPositions. The function uses the currently selected font to compute the dimensions of the string.

The current clipping region does not offset the width and height returned by the GetOutputTabbedTextExtent function.

Since some devices do not place characters in regular cell arrays (that is, they kern the characters), the sum of the extents of the characters in a string may not be equal to the extent of the string.

If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight average character widths. If nTabPositions is 1, the tab stops will be separated by the distance specified by the first value in the array to which lpnTabStopPositions points. If lpnTabStopPositions points to more than a single value, a tab stop is set for each value in the array, up to the number specified by nTabPositions.

CDC::GetOutputTextExtent

Call this member function to use the output device context, m_hDC, and compute the width and height of a line of text, using the current font.

CSize GetOutputTextExtent(
    LPCTSTR lpszString,  
    int nCount) const;  
  
CSize GetOutputTextExtent(const CString& str) const;  

Parameters

lpszString
Points to a string of characters. You can also pass a CString object for this parameter.

nCount
Specifies the number of characters in the string. If nCount is –1, the length is calculated.

str
A CString object that contains the specified characters to be measured.

Return Value

The dimensions of the string (in logical units) returned in a CSize object.

Remarks

The current clipping region does not affect the width and height returned by GetOutputTextExtent.

Since some devices do not place characters in regular cell arrays (that is, they carry out kerning), the sum of the extents of the characters in a string may not be equal to the extent of the string.

CDC::GetOutputTextMetrics

Retrieves the metrics for the current font using m_hDC, the output device context.

BOOL GetOutputTextMetrics(LPTEXTMETRIC lpMetrics) const;  

Parameters

lpMetrics
Points to the TEXTMETRIC structure that receives the metrics.

Return Value

Nonzero if the function is successful; otherwise 0.

CDC::GetPath

Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context.

int GetPath(
    LPPOINT lpPoints,  
    LPBYTE lpTypes,  
    int nCount) const;  

Parameters

lpPoints
Points to an array of POINT data structures or CPoint objects where the line endpoints and curve control points are placed.

lpTypes
Points to an array of bytes where the vertex types are placed. Values are one of the following:

  • PT_MOVETO Specifies that the corresponding point in lpPoints starts a disjoint figure.

  • PT_LINETO Specifies that the previous point and the corresponding point in lpPoints are the endpoints of a line.

  • PT_BEZIERTO Specifies that the corresponding point in lpPoints is a control point or ending point for a Bzier curve.

PT_BEZIERTO types always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bzier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the end point (if hard-coded).

 A **PT_LINETO** or **PT_BEZIERTO** type may be combined with the following flag (by using the bitwise operator `OR`) to indicate that the corresponding point is the last point in a figure and that the figure should be closed:  
  • PT_CLOSEFIGURE Specifies that the figure is automatically closed after the corresponding line or curve is drawn. The figure is closed by drawing a line from the line or curve endpoint to the point corresponding to the last PT_MOVETO.

nCount
Specifies the total number of POINT data structures that may be placed in the lpPoints array. This value must be the same as the number of bytes that may be placed in the lpTypes array.

Return Value

If the nCount parameter is nonzero, the number of points enumerated. If nCount is 0, the total number of points in the path (and GetPath writes nothing to the buffers). If nCount is nonzero and is less than the number of points in the path, the return value is -1.

Remarks

The device context must contain a closed path. The points of the path are returned in logical coordinates. Points are stored in the path in device coordinates, so GetPath changes the points from device coordinates to logical coordinates by using the inverse of the current transformation. The FlattenPath member function may be called before GetPath, to convert all curves in the path into line segments.

Example

See the example for CDC::BeginPath.

CDC::GetPixel

Retrieves the RGB color value of the pixel at the point specified by x and y.

COLORREF GetPixel(
    int x,  
    int y) const;  
  
COLORREF GetPixel(POINT point) const;  

Parameters

x
Specifies the logical x-coordinate of the point to be examined.

y
Specifies the logical y-coordinate of the point to be examined.

point
Specifies the logical x- and y-coordinates of the point to be examined.

Return Value

For either version of the function, an RGB color value for the color of the given point. It is –1 if the coordinates do not specify a point in the clipping region.

Remarks

The point must be in the clipping region. If the point is not in the clipping region, the function has no effect and returns –1.

Not all devices support the GetPixel function. For more information, see the RC_BITBLT raster capability under the GetDeviceCaps member function.

The GetPixel member function has two forms. The first takes two coordinate values; the second takes either a POINT structure or a CPoint object.

CDC::GetPolyFillMode

Retrieves the current polygon-filling mode.

int GetPolyFillMode() const;  

Return Value

The current polygon-filled mode, ALTERNATE or WINDING, if the function is successful.

Remarks

See the SetPolyFillMode member function for a description of the polygon-filling modes.

CDC::GetROP2

Retrieves the current drawing mode.

int GetROP2() const;  

Return Value

The drawing mode. For a list of the drawing mode values, see the SetROP2 member function.

Remarks

The drawing mode specifies how the colors of the pen and the interior of filled objects are combined with the color already on the display surface.

CDC::GetSafeHdc

Call this member function to get m_hDC, the output device context.

HDC GetSafeHdc() const;  

Return Value

A device context handle.

Remarks

This member function also works with null pointers.

CDC::GetStretchBltMode

Retrieves the current bitmap-stretching mode.

int GetStretchBltMode() const;  

Return Value

The return value specifies the current bitmap-stretching mode — STRETCH_ANDSCANS, STRETCH_DELETESCANS, or STRETCH_ORSCANS — if the function is successful.

Remarks

The bitmap-stretching mode defines how information is removed from bitmaps that are stretched or compressed by the StretchBlt member function.

The STRETCH_ANDSCANS and STRETCH_ORSCANS modes are typically used to preserve foreground pixels in monochrome bitmaps. The STRETCH_DELETESCANS mode is typically used to preserve color in color bitmaps.

CDC::GetTabbedTextExtent

Call this member function to compute the width and height of a character string using m_hAttribDC, the attribute device context.

CSize GetTabbedTextExtent(
    LPCTSTR lpszString,  
    int nCount,  
    int nTabPositions,  
    LPINT lpnTabStopPositions) const;  
  
CSize GetTabbedTextExtent(
    const CString& str,  
    int nTabPositions,  
    LPINT lpnTabStopPositions) const;  

Parameters

lpszString
Points to a character string. You can also pass a CString object for this parameter.

nCount
Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions
Specifies the number of tab-stop positions in the array pointed to by lpnTabStopPositions.

lpnTabStopPositions
Points to an array of integers containing the tab-stop positions in logical units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array. Back tabs are not allowed.

str
A CString object that contains the specified characters to be drawn.

Return Value

The dimensions of the string (in logical units) in a CSize object.

Remarks

If the string contains one or more tab characters, the width of the string is based upon the tab stops specified by lpnTabStopPositions. The function uses the currently selected font to compute the dimensions of the string.

The current clipping region does not offset the width and height returned by the GetTabbedTextExtent function.

Since some devices do not place characters in regular cell arrays (that is, they kern the characters), the sum of the extents of the characters in a string may not be equal to the extent of the string.

If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight times the average character width. If nTabPositions is 1, the tab stops will be separated by the distance specified by the first value in the array to which lpnTabStopPositions points. If lpnTabStopPositions points to more than a single value, a tab stop is set for each value in the array, up to the number specified by nTabPositions.

CDC::GetTextAlign

Retrieves the status of the text-alignment flags for the device context.

UINT GetTextAlign() const;  

Return Value

The status of the text-alignment flags. The return value is one or more of the following values:

  • TA_BASELINE Specifies alignment of the x-axis and the baseline of the chosen font within the bounding rectangle.

  • TA_BOTTOM Specifies alignment of the x-axis and the bottom of the bounding rectangle.

  • TA_CENTER Specifies alignment of the y-axis and the center of the bounding rectangle.

  • TA_LEFT Specifies alignment of the y-axis and the left side of the bounding rectangle.

  • TA_NOUPDATECP Specifies that the current position is not updated.

  • TA_RIGHT Specifies alignment of the y-axis and the right side of the bounding rectangle.

  • TA_TOP Specifies alignment of the x-axis and the top of the bounding rectangle.

  • TA_UPDATECP Specifies that the current position is updated.

Remarks

The text-alignment flags determine how the TextOut and ExtTextOut member functions align a string of text in relation to the string's starting point. The text-alignment flags are not necessarily single-bit flags and may be equal to 0. To test whether a flag is set, an application should follow these steps:

  1. Apply the bitwise OR operator to the flag and its related flags, grouped as follows:

    • TA_LEFT, TA_CENTER, and TA_RIGHT

    • TA_BASELINE, TA_BOTTOM, and TA_TOP

    • TA_NOUPDATECP and TA_UPDATECP

  2. Apply the bitwise-AND operator to the result and the return value of GetTextAlign.

  3. Test for the equality of this result and the flag.

CDC::GetTextCharacterExtra

Retrieves the current setting for the amount of intercharacter spacing.

int GetTextCharacterExtra() const;  

Return Value

The amount of the intercharacter spacing.

Remarks

GDI adds this spacing to each character, including break characters, when it writes a line of text to the device context.

The default value for the amount of intercharacter spacing is 0.

CDC::GetTextColor

Retrieves the current text color.

COLORREF GetTextColor() const;  

Return Value

The current text color as an RGB color value.

Remarks

The text color is the foreground color of characters drawn by using the GDI text-output member functions TextOut, ExtTextOut, and TabbedTextOut.

CDC::GetTextExtent

Call this member function to compute the width and height of a line of text using the current font to determine the dimensions.

CSize GetTextExtent(
    LPCTSTR lpszString,  
    int nCount) const;  
  
CSize GetTextExtent(const CString& str) const;  

Parameters

lpszString
Points to a string of characters. You can also pass a CString object for this parameter.

nCount
Specifies the number of characters in the string.

str
A CString object that contains the specified characters.

Return Value

The dimensions of the string (in logical units) in a CSize object.

Remarks

The information is retrieved from m_hAttribDC, the attribute device context.

By default, GetTextExtent assumes the text for which it retrieves the dimension is set along a horizontal line (that is, the escapement is 0). If you create a font specifying a non-zero escapement, you must convert the angle of the text explicitly to get the dimensions of the string.

The current clipping region does not affect the width and height returned by GetTextExtent.

Since some devices do not place characters in regular cell arrays (that is, they carry out kerning), the sum of the extents of the characters in a string may not be equal to the extent of the string.

CDC::GetTextExtentExPointI

Retrieves the number of characters in a specified string that will fit within a specified space and fills an array with the text extent for each of those characters.

BOOL GetTextExtentExPointI(
    LPWORD pgiIn,  
    int cgi,  
    int nMaxExtent,  
    LPINT lpnFit,  
    LPINT alpDx,  
    LPSIZE lpSize) const;  

Parameters

pgiIn
A pointer to an array of glyph indices for which extents are to be retrieved.

cgi
Specifies the number of glyphs in the array pointed to by pgiIn.

nMaxExtent
Specifies the maximum allowable width, in logical units, of the formatted string.

lpnFit
A pointer to an integer that receives a count of the maximum number of characters that will fit in the space specified by nMaxExtent. When lpnFit is NULL, nMaxExtent is ignored.

alpDx
A pointer to an array of integers that receives partial glyph extents. Each element in the array gives the distance, in logical units, between the beginning of the glyph indices array and one of the glyphs that fits in the space specified by nMaxExtent. Although this array should have at least as many elements as glyph indices specified by cgi, the function fills the array with extents only for as many glyph indices as are specified by lpnFit. If lpnDx is NULL, the function does not compute partial string widths.

lpSize
Pointer to a SIZE structure that receives the dimensions of the glyph indices array, in logical units. This value cannot be NULL.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This member function emulates the functionality of the function GetTextExtentExPointI, as described in the Windows SDK.

CDC::GetTextExtentPointI

Retrieves the width and height of the specified array of glyph indices.

BOOL GetTextExtentPointI(
    LPWORD pgiIn,  
    int cgi,  
    LPSIZE lpSize) const;  

Parameters

pgiIn
A pointer to an array of glyph indices for which extents are to be retrieved.

cgi
Specifies the number of glyphs in the array pointed to by pgiIn.

lpSize
Pointer to a SIZE structure that receives the dimensions of the glyph indices array, in logical units. This value cannot be NULL.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This member function emulates the functionality of the function GetTextExtentPointI, as described in the Windows SDK.

CDC::GetTextFace

Call this member function to copy the typeface name of the current font into a buffer.

int GetTextFace(
    int nCount,  
    LPTSTR lpszFacename) const;  
  
int GetTextFace(CString& rString) const;  

Parameters

nCount
Specifies the size of the buffer (in bytes). If the typeface name is longer than the number of bytes specified by this parameter, the name is truncated.

lpszFacename
Points to the buffer for the typeface name.

rString
A reference to a CString object.

Return Value

The number of bytes copied to the buffer, not including the terminating null character. It is 0 if an error occurs.

Remarks

The typeface name is copied as a null-terminated string.

CDC::GetTextMetrics

Retrieves the metrics for the current font using the attribute device context.

BOOL GetTextMetrics(LPTEXTMETRIC lpMetrics) const;  

Parameters

lpMetrics
Points to the TEXTMETRIC structure that receives the metrics.

Return Value

Nonzero if the function is successful; otherwise 0.

CDC::GetViewportExt

Retrieves the x- and y-extents of the device context's viewport.

CSize GetViewportExt() const;  

Return Value

The x- and y-extents (in device units) as a CSize object.

CDC::GetViewportOrg

Retrieves the x- and y-coordinates of the origin of the viewport associated with the device context.

CPoint GetViewportOrg() const;  

Return Value

The origin of the viewport (in device coordinates) as a CPoint object.

CDC::GetWindow

Returns the window associated with the display device context.

CWnd* GetWindow() const;  

Return Value

Pointer to a CWnd object if successful; otherwise NULL.

Remarks

This is an advanced function. For example, this member function may not return the view window when printing or in print preview. It always returns the window associated with output. Output functions that use the given DC draw into this window.

CDC::GetWindowExt

Retrieves the x- and y-extents of the window associated with the device context.

CSize GetWindowExt() const;  

Return Value

The x- and y-extents (in logical units) as a CSize object.

CDC::GetWindowOrg

Retrieves the x- and y-coordinates of the origin of the window associated with the device context.

CPoint GetWindowOrg() const;  

Return Value

The origin of the window (in logical coordinates) as a CPoint object.

CDC::GetWorldTransform

Retrieves the current world-space to page-space transformation.

BOOL GetWorldTransform(XFORM& rXform) const;  

Parameters

rXform
Reference to an XFORM structure that receives the current world-space to page-space transformation.

Return Value

Returns a nonzero value on success.

Returns 0 on failure.

To get extended error information, call GetLastError.

Remarks

This method wraps the Windows GDI function GetWorldTransform.

CDC::GradientFill

Call this member function to fill rectangle and triangle structures with color that smoothly fades from one side to the other.

BOOL GradientFill(
    TRIVERTEX* pVertices,  
    ULONG nVertices,  
    void* pMesh,  
    ULONG nMeshElements,  
    DWORD dwMode);

Parameters

pVertices
Pointer to an array of TRIVERTEX structures that each define a triangle vertex.

nVertices
The number of vertices.

pMesh
Array of GRADIENT_TRIANGLE structures in triangle mode, or an array of GRADIENT_RECT structures in rectangle mode.

nMeshElements
The number of elements (triangles or rectangles) in pMesh.

dwMode
Specifies gradient fill mode. For a list of possible values, see GradientFill in the Windows SDK.

Return Value

TRUE if successful; otherwise FALSE.

Remarks

For more information, see GradientFill in the Windows SDK.

CDC::GrayString

Draws dimmed (gray) text at the given location by writing the text in a memory bitmap, dimming the bitmap, and then copying the bitmap to the display.

virtual BOOL GrayString(
    CBrush* pBrush,  
    BOOL (CALLBACK* lpfnOutput)(
    HDC,
    LPARAM,
    int),  
    LPARAM lpData,  
    int nCount,  
    int x,  
    int y,  
    int nWidth,  
    int nHeight);

Parameters

pBrush
Identifies the brush to be used for dimming (graying).

lpfnOutput
Specifies the procedure-instance address of the application-supplied callback function that will draw the string. For more information, see the description of the Windows OutputFunc callback function. If this parameter is NULL, the system uses the Windows TextOut function to draw the string, and lpData is assumed to be a long pointer to the character string to be output.

lpData
Specifies a far pointer to data to be passed to the output function. If lpfnOutput is NULL, lpData must be a long pointer to the string to be output.

nCount
Specifies the number of characters to be output. If this parameter is 0, GrayString calculates the length of the string (assuming that lpData is a pointer to the string). If nCount is –1 and the function pointed to by lpfnOutput returns 0, the image is shown but not dimmed.

x
Specifies the logical x-coordinate of the starting position of the rectangle that encloses the string.

y
Specifies the logical y-coordinate of the starting position of the rectangle that encloses the string.

nWidth
Specifies the width (in logical units) of the rectangle that encloses the string. If nWidth is 0, GrayString calculates the width of the area, assuming lpData is a pointer to the string.

nHeight
Specifies the height (in logical units) of the rectangle that encloses the string. If nHeight is 0, GrayString calculates the height of the area, assuming lpData is a pointer to the string.

Return Value

Nonzero if the string is drawn, or 0 if either the TextOut function or the application-supplied output function returned 0, or if there was insufficient memory to create a memory bitmap for dimming.

Remarks

The function dims the text regardless of the selected brush and background. The GrayString member function uses the currently selected font. The MM_TEXT mapping mode must be selected before using this function.

An application can draw dimmed (grayed) strings on devices that support a solid gray color without calling the GrayString member function. The system color COLOR_GRAYTEXT is the solid-gray system color used to draw disabled text. The application can call the GetSysColor Windows function to retrieve the color value of COLOR_GRAYTEXT. If the color is other than 0 (black), the application can call the SetTextColor member function to set the text color to the color value and then draw the string directly. If the retrieved color is black, the application must call GrayString to dim (gray) the text.

If lpfnOutput is NULL, GDI uses the Windows TextOut function, and lpData is assumed to be a far pointer to the character to be output. If the characters to be output cannot be handled by the TextOut member function (for example, the string is stored as a bitmap), the application must supply its own output function.

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions.

The callback function passed to GrayString must use the __stdcall calling convention and must be exported with __declspec.

When the framework is in preview mode, a call to the GrayString member function is translated to a TextOut call, and the callback function is not called.

CDC::HIMETRICtoDP

Use this function when you convert HIMETRIC sizes from OLE to pixels.

void HIMETRICtoDP(LPSIZE lpSize) const;  

Parameters

lpSize
Points to a SIZE structure or CSize object.

Remarks

If the mapping mode of the device context object is MM_LOENGLISH, MM_HIENGLISH, MM_LOMETRIC or MM_HIMETRIC, then the conversion is based on the number of pixels in the physical inch. If the mapping mode is one of the other non-constrained modes (e.g., MM_TEXT), then the conversion is based on the number of pixels in the logical inch.

CDC::HIMETRICtoLP

Call this function to convert HIMETRIC units into logical units.

void HIMETRICtoLP(LPSIZE lpSize) const;  

Parameters

lpSize
Points to a SIZE structure or CSize object.

Remarks

Use this function when you get HIMETRIC sizes from OLE and wish to convert them to your application's natural mapping mode.

The conversion is accomplished by first converting the HIMETRIC units into pixels and then converting these units into logical units using the device context's current mapping units. Note that the extents of the device's window and viewport will affect the result.

CDC::IntersectClipRect

Creates a new clipping region by forming the intersection of the current region and the rectangle specified by x1, y1, x2, and y2.

int IntersectClipRect(
    int x1,  
    int y1,  
    int x2,  
    int y2);  
  
int IntersectClipRect(LPCRECT lpRect);

Parameters

x1
Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y1
Specifies the logical y-coordinate of the upper-left corner of the rectangle.

x2
Specifies the logical x-coordinate of the lower-right corner of the rectangle.

y2
Specifies the logical y-coordinate of the lower-right corner of the rectangle.

lpRect
Specifies the rectangle. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

Return Value

The new clipping region's type. It can be any one of the following values:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Remarks

GDI clips all subsequent output to fit within the new boundary. The width and height must not exceed 32,767.

CDC::InvertRect

Inverts the contents of the given rectangle.

void InvertRect(LPCRECT lpRect);

Parameters

lpRect
Points to a RECT that contains the logical coordinates of the rectangle to be inverted. You can also pass a CRect object for this parameter.

Remarks

Inversion is a logical NOT operation and flips the bits of each pixel. On monochrome displays, the function makes white pixels black and black pixels white. On color displays, the inversion depends on how colors are generated for the display. Calling InvertRect twice with the same rectangle restores the display to its previous colors.

If the rectangle is empty, nothing is drawn.

Example

void CDCView::DoInvertRect(CDC* pDC)
{
   // invert rect from 20,20 to 50,50
   CRect rect(20, 20, 50, 50);
   pDC->InvertRect(rect);

   // inverting again restores to normal
   ::Sleep(1000);
   pDC->InvertRect(rect);   
}

CDC::InvertRgn

Inverts the colors in the region specified by pRgn.

BOOL InvertRgn(CRgn* pRgn);

Parameters

pRgn
Identifies the region to be inverted. The coordinates for the region are specified in logical units.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

On monochrome displays, the function makes white pixels black and black pixels white. On color displays, the inversion depends on how the colors are generated for the display.

CDC::IsPrinting

Determines whether the device context is being used for printing.

BOOL IsPrinting() const;  

Return Value

Nonzero if the CDC object is a printer DC; otherwise 0.

CDC::LineTo

Draws a line from the current position up to, but not including, the point specified by x and y (or point).

BOOL LineTo(
    int x,  
    int y);  
  
BOOL LineTo(POINT point);

Parameters

x
Specifies the logical x-coordinate of the endpoint for the line.

y
Specifies the logical y-coordinate of the endpoint for the line.

point
Specifies the endpoint for the line. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the line is drawn; otherwise 0.

Remarks

The line is drawn with the selected pen. The current position is set to x, y or to point.

Example

See the example for CRect::CenterPoint.

CDC::LPtoDP

Converts logical units into device units.

void LPtoDP(
    LPPOINT lpPoints,  
    int nCount = 1) const;  
  
void LPtoDP(LPRECT lpRect) const;
void LPtoDP(LPSIZE lpSize) const;  

Parameters

lpPoints
Points to an array of points. Each point in the array is a POINT structure or a CPoint object.

nCount
The number of points in the array.

lpRect
Points to a RECT structure or a CRect object. This parameter is used for the common case of mapping a rectangle from logical to device units.

lpSize
Points to a SIZE structure or a CSize object.

Remarks

The function maps the coordinates of each point, or dimensions of a size, from GDI's logical coordinate system into a device coordinate system. The conversion depends on the current mapping mode and the settings of the origins and extents of the device's window and viewport.

The x- and y-coordinates of points are 2-byte signed integers in the range –32,768 through 32,767. In cases where the mapping mode would result in values larger than these limits, the system sets the values to –32,768 and 32,767, respectively.

CDC::LPtoHIMETRIC

Call this function to convert logical units into HIMETRIC units.

void LPtoHIMETRIC(LPSIZE lpSize) const;  

Parameters

lpSize
Points to a SIZE structure or a CSize object.

Remarks

Use this function when you give HIMETRIC sizes to OLE, converting from your application's natural mapping mode. Note that the extents of the device's window and viewport will affect the result.

The conversion is accomplished by first converting the logical units into pixels using the device context's current mapping units and then converting these units into HIMETRIC units.

CDC::m_hAttribDC

The attribute device context for this CDC object.

HDC m_hAttribDC;  

Remarks

By default, this device context is equal to m_hDC. In general, CDC GDI calls that request information from the device context are directed to m_hAttribDC. See the CDC class description for more on the use of these two device contexts.

CDC::m_hDC

The output device context for this CDC object.

HDC m_hDC;  

Remarks

By default, m_hDC is equal to m_hAttribDC, the other device context wrapped by CDC. In general, CDC GDI calls that create output go to the m_hDC device context. You can initialize m_hDC and m_hAttribDC to point to different devices. See the CDC class description for more on the use of these two device contexts.

CDC::MaskBlt

Combines the color data for the source and destination bitmaps using the given mask and raster operation.

BOOL MaskBlt(
    int x,  
    int y,  
    int nWidth,  
    int nHeight,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    CBitmap& maskBitmap,  
    int xMask,  
    int yMask,  
    DWORD dwRop);

Parameters

x
Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

y
Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth
Specifies the width, in logical units, of the destination rectangle and source bitmap.

nHeight
Specifies the height, in logical units, of the destination rectangle and source bitmap.

pSrcDC
Identifies the device context from which the bitmap is to be copied. It must be zero if the dwRop parameter specifies a raster operation that does not include a source.

xSrc
Specifies the logical x-coordinate of the upper-left corner of the source bitmap.

ySrc
Specifies the logical y-coordinate of the upper-left corner of the source bitmap.

maskBitmap
Identifies the monochrome mask bitmap combined with the color bitmap in the source device context.

xMask
Specifies the horizontal pixel offset for the mask bitmap specified by the maskBitmap parameter.

yMask
Specifies the vertical pixel offset for the mask bitmap specified by the maskBitmap parameter.

dwRop
Specifies both foreground and background ternary raster operation codes, which the function uses to control the combination of source and destination data. The background raster operation code is stored in the high byte of the high word of this value; the foreground raster operation code is stored in the low byte of the high word of this value; the low word of this value is ignored, and should be zero. The macro MAKEROP4 creates such combinations of foreground and background raster operation codes. See the Remarks section for a discussion of foreground and background in the context of this function. See the BitBlt member function for a list of common raster operation codes.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

A value of 1 in the mask specified by maskBitmap indicates that the foreground raster operation code specified by dwRop should be applied at that location. A value of 0 in the mask indicates that the background raster operation code specified by dwRop should be applied at that location. If the raster operations require a source, the mask rectangle must cover the source rectangle. If it does not, the function will fail. If the raster operations do not require a source, the mask rectangle must cover the destination rectangle. If it does not, the function will fail.

If a rotation or shear transformation is in effect for the source device context when this function is called, an error occurs. However, other types of transformations are allowed.

If the color formats of the source, pattern, and destination bitmaps differ, this function converts the pattern or source format, or both, to match the destination format. If the mask bitmap is not a monochrome bitmap, an error occurs. When an enhanced metafile is being recorded, an error occurs (and the function returns 0) if the source device context identifies an enhanced-metafile device context. Not all devices support MaskBlt. An application should call GetDeviceCaps to determine whether a device supports this function. If no mask bitmap is supplied, this function behaves exactly like BitBlt, using the foreground raster operation code. The pixel offsets in the mask bitmap map to the point (0,0) in the source device context's bitmap. This is useful for cases in which a mask bitmap contains a set of masks; an application can easily apply any one of them to a mask-blitting task by adjusting the pixel offsets and rectangle sizes sent to MaskBlt.

CDC::ModifyWorldTransform

Changes the world transformation for a device context using the specified mode.

BOOL ModifyWorldTransform(
    const XFORM& rXform,  
    DWORD iMode);

Parameters

rXform
Reference to an XFORM structure used to modify the world transformation for the given device context.

iMode
Specifies how the transformation data modifies the current world transformation. For a list of the values that this parameter can take, see ModifyWorldTransform.

Return Value

Returns a nonzero value on success.

Returns 0 on failure.

To get extended error information, call GetLastError.

Remarks

This method wraps the Windows GDI function ModifyWorldTransform.

CDC::MoveTo

Moves the current position to the point specified by x and y (or by point).

CPoint MoveTo(
    int x,  
    int y);  
  
CPoint MoveTo(POINT point);

Parameters

x
Specifies the logical x-coordinate of the new position.

y
Specifies the logical y-coordinate of the new position.

point
Specifies the new position. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

The x- and y-coordinates of the previous position as a CPoint object.

Example

See the example for CRect::CenterPoint.

CDC::OffsetClipRgn

Moves the clipping region of the device context by the specified offsets.

int OffsetClipRgn(
    int x,  
    int y);  
  
int OffsetClipRgn(SIZE size);

Parameters

x
Specifies the number of logical units to move left or right.

y
Specifies the number of logical units to move up or down.

size
Specifies the amount to offset.

Return Value

The new region's type. It can be any one of the following values:

  • COMPLEXREGION Clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION Clipping region is empty.

  • SIMPLEREGION Clipping region has no overlapping borders.

Remarks

The function moves the region x units along the x-axis and y units along the y-axis.

CDC::OffsetViewportOrg

Modifies the coordinates of the viewport origin relative to the coordinates of the current viewport origin.

virtual CPoint OffsetViewportOrg(
    int nWidth,  
    int nHeight);

Parameters

nWidth
Specifies the number of device units to add to the current origin's x-coordinate.

nHeight
Specifies the number of device units to add to the current origin's y-coordinate.

Return Value

The previous viewport origin (in device coordinates) as a CPoint object.

CDC::OffsetWindowOrg

Modifies the coordinates of the window origin relative to the coordinates of the current window origin.

CPoint OffsetWindowOrg(
    int nWidth,  
    int nHeight);

Parameters

nWidth
Specifies the number of logical units to add to the current origin's x-coordinate.

nHeight
Specifies the number of logical units to add to the current origin's y-coordinate.

Return Value

The previous window origin (in logical coordinates) as a CPoint object.

CDC::operator HDC

Use this operator to retrieve the device context handle of the CDC object.

operator HDC() const;  

Return Value

If successful, the handle of the device context object; otherwise, NULL.

Remarks

You can use the handle to call Windows APIs directly.

CDC::PaintRgn

Fills the region specified by pRgn using the current brush.

BOOL PaintRgn(CRgn* pRgn);

Parameters

pRgn
Identifies the region to be filled. The coordinates for the given region are specified in logical units.

Return Value

Nonzero if the function is successful; otherwise 0.

CDC::PatBlt

Creates a bit pattern on the device.

BOOL PatBlt(
    int x,  
    int y,  
    int nWidth,  
    int nHeight,  
    DWORD dwRop);

Parameters

x
Specifies the logical x-coordinate of the upper-left corner of the rectangle that is to receive the pattern.

y
Specifies the logical y-coordinate of the upper-left corner of the rectangle that is to receive the pattern.

nWidth
Specifies the width (in logical units) of the rectangle that is to receive the pattern.

nHeight
Specifies the height (in logical units) of the rectangle that is to receive the pattern.

dwRop
Specifies the raster-operation code. Raster-operation codes (ROPs) define how GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. This parameter can be one of the following values:

  • PATCOPY Copies pattern to destination bitmap.

  • PATINVERT Combines destination bitmap with pattern using the Boolean XOR operator.

  • DSTINVERT Inverts the destination bitmap.

  • BLACKNESS Turns all output black.

  • WHITENESS Turns all output white.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The pattern is a combination of the selected brush and the pattern already on the device. The raster-operation code specified by dwRop defines how the patterns are to be combined. The raster operations listed for this function are a limited subset of the full 256 ternary raster-operation codes; in particular, a raster-operation code that refers to a source cannot be used.

Not all device contexts support the PatBlt function. To determine whether a device context supports PatBlt, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_BITBLT flag.

CDC::Pie

Draws a pie-shaped wedge by drawing an elliptical arc whose center and two endpoints are joined by lines.

BOOL Pie(
    int x1,  
    int y1,  
    int x2,  
    int y2,  
    int x3,  
    int y3,  
    int x4,  
    int y4);

 
BOOL Pie(
    LPCRECT lpRect,
    POINT ptStart,
    POINT ptEnd);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3
Specifies the x-coordinate of the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

y3
Specifies the y-coordinate of the arc's starting point (in logical units). This point does not have to lie exactly on the arc.

x4
Specifies the x-coordinate of the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

y4
Specifies the y-coordinate of the arc's endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect
Specifies the bounding rectangle. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

ptStart
Specifies the starting point of the arc. This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd
Specifies the endpoint of the arc. This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The center of the arc is the center of the bounding rectangle specified by x1, y1, x2, and y2 (or by lpRect). The starting and ending points of the arc are specified by x3, y3, x4, and y4 (or by ptStart and ptEnd).

The arc is drawn with the selected pen, moving in a counterclockwise direction. Two additional lines are drawn from each endpoint to the arc's center. The pie-shaped area is filled with the current brush. If x3 equals x4 and y3 equals y4, the result is an ellipse with a single line from the center of the ellipse to the point ( x3, y3) or ( x4, y4).

The figure drawn by this function extends up to but does not include the right and bottom coordinates. This means that the height of the figure is y2y1 and the width of the figure is x2x1. Both the width and the height of the bounding rectangle must be greater than 2 units and less than 32,767 units.

Example

void CDCView::DrawPie(CDC* pDC)
{
   // Fill the client area with a simple pie chart. A
   // big blue slice covers 75% of the pie, from
   // 6 o'clock to 3 o'clock. This portion is filled
   // with blue and has a blue edge. The remaining 25%
   // is filled with a red, diagonal hatch and has
   // a red edge.

   // Get the client area.
   CRect rectClient;
   GetClientRect(rectClient);

   // Make a couple of pens and similar brushes.
   CPen penBlue, penRed;
   CBrush brushBlue, brushRed;
   CBrush* pOldBrush;
   CPen* pOldPen;

   brushBlue.CreateSolidBrush(RGB(0, 0, 255));
   brushRed.CreateHatchBrush(HS_FDIAGONAL, RGB(255, 0, 0));
   penBlue.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(0, 0, 255));
   penRed.CreatePen(PS_SOLID | PS_COSMETIC, 1, RGB(255, 0, 0));

   // Draw from 3 o'clock to 6 o'clock, counterclockwise,
   // in a blue pen with a solid blue fill.

   pOldPen = pDC->SelectObject(&penBlue);
   pOldBrush = pDC->SelectObject(&brushBlue);

   pDC->Pie(rectClient,
      CPoint(rectClient.right, rectClient.CenterPoint().y),
      CPoint(rectClient.CenterPoint().x, rectClient.right));

   // Draw the remaining quarter slice from 6 o'clock
   // to 3 o'clock, counterclockwise, in a red pen with
   // the hatched brush.
   pDC->SelectObject(&penRed);
   pDC->SelectObject(&brushRed);

   // Same parameters, but reverse start and end points.
   pDC->Pie(rectClient,
      CPoint(rectClient.CenterPoint().x, rectClient.right),
      CPoint(rectClient.right, rectClient.CenterPoint().y));

   // Restore the previous pen.
   pDC->SelectObject(pOldPen);
}

CDC::PlayMetaFile

Plays the contents of the specified metafile on the device context.

BOOL PlayMetaFile(HMETAFILE hMF);

 
BOOL PlayMetaFile(
    HENHMETAFILE hEnhMetaFile,  
    LPCRECT lpBounds);

Parameters

hMF
Identifies the metafile to be played.

hEnhMetaFile
Identifies the enhanced metafile.

lpBounds
Points to a RECT structure or a CRect object that contains the coordinates of the bounding rectangle used to display the picture. The coordinates are specified in logical units.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The metafile can be played any number of times.

The second version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. When an application calls the second version of PlayMetaFile, Windows uses the picture frame in the enhanced-metafile header to map the picture onto the rectangle pointed to by the lpBounds parameter. (This picture may be sheared or rotated by setting the world transform in the output device before calling PlayMetaFile.) Points along the edges of the rectangle are included in the picture. An enhanced-metafile picture can be clipped by defining the clipping region in the output device before playing the enhanced metafile.

If an enhanced metafile contains an optional palette, an application can achieve consistent colors by setting up a color palette on the output device before calling the second version of PlayMetaFile. To retrieve the optional palette, use the GetEnhMetaFilePaletteEntries Windows function. An enhanced metafile can be embedded in a newly created enhanced metafile by calling the second version of PlayMetaFile and playing the source enhanced metafile into the device context for the new enhanced metafile.

The states of the output device context are preserved by this function. Any object created but not deleted in the enhanced metafile is deleted by this function. To stop this function, an application can call the CancelDC Windows function from another thread to terminate the operation. In this case, the function returns zero.

CDC::PlgBlt

Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context.

BOOL PlgBlt(
    LPPOINT lpPoint,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    int nWidth,  
    int nHeight,  
    CBitmap& maskBitmap,  
    int xMask,  
    int yMask);

Parameters

lpPoint
Points to an array of three points in logical space that identifies three corners of the destination parallelogram. The upper-left corner of the source rectangle is mapped to the first point in this array, the upper-right corner to the second point in this array, and the lower-left corner to the third point. The lower-right corner of the source rectangle is mapped to the implicit fourth point in the parallelogram.

pSrcDC
Identifies the source device context.

xSrc
Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.

ySrc
Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.

nWidth
Specifies the width, in logical units, of the source rectangle.

nHeight
Specifies the height, in logical units, of the source rectangle.

maskBitmap
Identifies an optional monochrome bitmap that is used to mask the colors of the source rectangle.

xMask
Specifies the x-coordinate of the upper-left corner of the monochrome bitmap.

yMask
Specifies the y-coordinate of the upper-left corner of the monochrome bitmap.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

If the given bitmask handle identifies a valid monochrome bitmap, the function uses this bitmap to mask the bits of color data from the source rectangle.

The fourth vertex of the parallelogram (D) is defined by treating the first three points (A, B, and C) as vectors and computing D = B + C - A.

If the bitmask exists, a value of 1 in the mask indicates that the source pixel color should be copied to the destination. A value of 0 in the mask indicates that the destination pixel color is not to be changed.

If the mask rectangle is smaller than the source and destination rectangles, the function replicates the mask pattern.

Scaling, translation, and reflection transformations are allowed in the source device context; however, rotation and shear transformations are not. If the mask bitmap is not a monochrome bitmap, an error occurs. The stretching mode for the destination device context is used to determine how to stretch or compress the pixels, if that is necessary. When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.

The destination coordinates are transformed according to the destination device context; the source coordinates are transformed according to the source device context. If the source transformation has a rotation or shear, an error is returned. If the destination and source rectangles do not have the same color format, PlgBlt converts the source rectangle to match the destination rectangle. Not all devices support PlgBlt. For more information, see the description of the RC_BITBLT raster capability in the CDC::GetDeviceCaps member function.

If the source and destination device contexts represent incompatible devices, PlgBlt returns an error.

CDC::PolyBezier

Draws one or more Bzier splines.

BOOL PolyBezier(
    const POINT* lpPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT data structures that contain the endpoints and control points of the spline(s).

nCount
Specifies the number of points in the lpPoints array. This value must be one more than three times the number of splines to be drawn, because each Bzier spline requires two control points and an endpoint, and the initial spline requires an additional starting point.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This function draws cubic Bzier splines by using the endpoints and control points specified by the lpPoints parameter. The first spline is drawn from the first point to the fourth point by using the second and third points as control points. Each subsequent spline in the sequence needs exactly three more points: the end point of the previous spline is used as the starting point, the next two points in the sequence are control points, and the third is the end point.

The current position is neither used nor updated by the PolyBezier function. The figure is not filled. This function draws lines by using the current pen.

CDC::PolyBezierTo

Draws one or more Bzier splines.

BOOL PolyBezierTo(
    const POINT* lpPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT data structures that contains the endpoints and control points.

nCount
Specifies the number of points in the lpPoints array. This value must be three times the number of splines to be drawn, because each Bzier spline requires two control points and an end point.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This function draws cubic Bzier splines by using the control points specified by the lpPoints parameter. The first spline is drawn from the current position to the third point by using the first two points as control points. For each subsequent spline, the function needs exactly three more points, and uses the end point of the previous spline as the starting point for the next. PolyBezierTo moves the current position to the end point of the last Bzier spline. The figure is not filled. This function draws lines by using the current pen.

Example

See the example for CDC::BeginPath.

CDC::PolyDraw

Draws a set of line segments and Bzier splines.

BOOL PolyDraw(
    const POINT* lpPoints,  
    const BYTE* lpTypes,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT data structures that contains the endpoints for each line segment and the endpoints and control points for each Bzier spline.

lpTypes
Points to an array that specifies how each point in the lpPoints array is used. Values can be one of the following:

  • PT_MOVETO Specifies that this point starts a disjoint figure. This point becomes the new current position.

  • PT_LINETO Specifies that a line is to be drawn from the current position to this point, which then becomes the new current position.

  • PT_BEZIERTO Specifies that this point is a control point or ending point for a Bzier spline.

PT_BEZIERTO types always occur in sets of three. The current position defines the starting point for the Bzier spline. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending point. The ending point becomes the new current position. If there are not three consecutive PT_BEZIERTO points, an error results.

 A **PT_LINETO** or **PT_BEZIERTO** type can be combined with the following constant by using the bitwise operator OR to indicate that the corresponding point is the last point in a figure and the figure is closed:  
  • PT_CLOSEFIGURE Specifies that the figure is automatically closed after the PT_LINETO or PT_BEZIERTO type for this point is done. A line is drawn from this point to the most recent PT_MOVETO or MoveTo point.

    This flag is combined with the PT_LINETO type for a line, or with the PT_BEZIERTO type of ending point for a Bzier spline, by using the bitwise OR operator. The current position is set to the ending point of the closing line.

nCount
Specifies the total number of points in the lpPoints array, the same as the number of bytes in the lpTypes array.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This function can be used to draw disjoint figures in place of consecutive calls to CDC::MoveTo, CDC::LineTo, and CDC::PolyBezierTo member functions. The lines and splines are drawn using the current pen, and figures are not filled. If there is an active path started by calling the CDC::BeginPath member function, PolyDraw adds to the path. The points contained in the lpPoints array and in lpTypes indicate whether each point is part of a CDC::MoveTo, a CDC::LineTo, or a CDC::BezierTo operation. It is also possible to close figures. This function updates the current position.

Example

See the example for CDC::BeginPath.

CDC::Polygon

Draws a polygon consisting of two or more points (vertices) connected by lines, using the current pen.

BOOL Polygon(
    LPPOINT lpPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of points that specifies the vertices of the polygon. Each point in the array is a POINT structure or a CPoint object.

nCount
Specifies the number of vertices in the array.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The system closes the polygon automatically, if necessary, by drawing a line from the last vertex to the first.

The current polygon-filling mode can be retrieved or set by using the GetPolyFillMode and SetPolyFillMode member functions.

Example

void CDCView::DrawPolygon(CDC* pDC)
{
   // find the client area
   CRect rect;
   GetClientRect(rect);

   // draw with a thick blue pen
   CPen penBlue(PS_SOLID, 5, RGB(0, 0, 255));
   CPen* pOldPen = pDC->SelectObject(&penBlue);

   // and a solid red brush
   CBrush brushRed(RGB(255, 0, 0));
   CBrush* pOldBrush = pDC->SelectObject(&brushRed);

   // Find the midpoints of the top, right, left, and bottom
   // of the client area. They will be the vertices of our polygon.
   CPoint pts[4];
   pts[0].x = rect.left + rect.Width()/2;
   pts[0].y = rect.top;

   pts[1].x = rect.right;
   pts[1].y = rect.top + rect.Height()/2;

   pts[2].x = pts[0].x;
   pts[2].y = rect.bottom;

   pts[3].x = rect.left;
   pts[3].y = pts[1].y;

   // Calling Polygon() on that array will draw three lines
   // between the points, as well as an additional line to
   // close the shape--from the last point to the first point
   // we specified.
   pDC->Polygon(pts, 4);

   // Put back the old objects.
   pDC->SelectObject(pOldPen);
   pDC->SelectObject(pOldBrush);
}

CDC::Polyline

Draws a set of line segments connecting the points specified by lpPoints.

BOOL Polyline(
    LPPOINT lpPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT structures or CPoint objects to be connected.

nCount
Specifies the number of points in the array. This value must be at least 2.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The lines are drawn from the first point through subsequent points using the current pen. Unlike the LineTo member function, the Polyline function neither uses nor updates the current position.

For more information, see PolyLine in the Windows SDK.

CDC::PolylineTo

Draws one or more straight lines.

BOOL PolylineTo(
    const POINT* lpPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT data structures that contains the vertices of the line.

nCount
Specifies the number of points in the array.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

A line is drawn from the current position to the first point specified by the lpPoints parameter by using the current pen. For each additional line, the function draws from the ending point of the previous line to the next point specified by lpPoints. PolylineTo moves the current position to the ending point of the last line. If the line segments drawn by this function form a closed figure, the figure is not filled.

CDC::PolyPolygon

Creates two or more polygons that are filled using the current polygon-filling mode.

BOOL PolyPolygon(
    LPPOINT lpPoints,  
    LPINT lpPolyCounts,  
    int nCount);

Parameters

lpPoints
Points to an array of POINT structures or CPoint objects that define the vertices of the polygons.

lpPolyCounts
Points to an array of integers, each of which specifies the number of points in one of the polygons in the lpPoints array.

nCount
The number of entries in the lpPolyCounts array. This number specifies the number of polygons to be drawn. This value must be at least 2.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The polygons may be disjoint or overlapping.

Each polygon specified in a call to the PolyPolygon function must be closed. Unlike polygons created by the Polygon member function, the polygons created by PolyPolygon are not closed automatically.

The function creates two or more polygons. To create a single polygon, an application should use the Polygon member function.

The current polygon-filling mode can be retrieved or set by using the GetPolyFillMode and SetPolyFillMode member functions.

CDC::PolyPolyline

Draws multiple series of connected line segments.

BOOL PolyPolyline(
    const POINT* lpPoints,  
    const DWORD* lpPolyPoints,  
    int nCount);

Parameters

lpPoints
Points to an array of structures that contains the vertices of the polylines. The polylines are specified consecutively.

lpPolyPoints
Points to an array of variables specifying the number of points in the lpPoints array for the corresponding polygon. Each entry must be greater than or equal to 2.

nCount
Specifies the total number of counts in the lpPolyPoints array.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The line segments are drawn by using the current pen. The figures formed by the segments are not filled. The current position is neither used nor updated by this function.

CDC::PtVisible

Determines whether the given point is within the clipping region of the device context.

virtual BOOL PtVisible(
    int x,  
    int y) const;  
  
BOOL PtVisible(POINT point) const;  

Parameters

x
Specifies the logical x-coordinate of the point.

y
Specifies the logical y-coordinate of the point.

point
Specifies the point to check in logical coordinates. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the specified point is within the clipping region; otherwise 0.

CDC::QueryAbort

Calls the abort function installed by the SetAbortProc member function for a printing application and queries whether the printing should be terminated.

BOOL QueryAbort() const;  

Return Value

The return value is nonzero if printing should continue or if there is no abort procedure. It is 0 if the print job should be terminated. The return value is supplied by the abort function.

CDC::RealizePalette

Maps entries from the current logical palette to the system palette.

UINT RealizePalette();

Return Value

Indicates how many entries in the logical palette were mapped to different entries in the system palette. This represents the number of entries that this function remapped to accommodate changes in the system palette since the logical palette was last realized.

Remarks

A logical color palette acts as a buffer between color-intensive applications and the system, allowing an application to use as many colors as needed without interfering with its own displayed colors or with colors displayed by other windows.

When a window has the input focus and calls RealizePalette, Windows ensures that the window will display all the requested colors, up to the maximum number simultaneously available on the screen. Windows also displays colors not found in the window's palette by matching them to available colors.

In addition, Windows matches the colors requested by inactive windows that call the function as closely as possible to the available colors. This significantly reduces undesirable changes in the colors displayed in inactive windows.

CDC::Rectangle

Draws a rectangle using the current pen.

BOOL Rectangle(
    int x1,  
    int y1,  
    int x2,  
    int y2);  
  
BOOL Rectangle(LPCRECT lpRect);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the rectangle (in logical units).

lpRect
Specifies the rectangle in logical units. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The interior of the rectangle is filled using the current brush.

The rectangle extends up to, but does not include, the right and bottom coordinates. This means that the height of the rectangle is y2y1 and the width of the rectangle is x2x1. Both the width and the height of a rectangle must be greater than 2 units and less than 32,767 units.

Example

void CDCView::DrawRectangle(CDC* pDC)
{
   // create and select a solid blue brush
   CBrush brushBlue(RGB(0, 0, 255));
   CBrush* pOldBrush = pDC->SelectObject(&brushBlue);

   // create and select a thick, black pen
   CPen penBlack;
   penBlack.CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
   CPen* pOldPen = pDC->SelectObject(&penBlack);

   // get our client rectangle
   CRect rect;
   GetClientRect(rect);

   // shrink our rect 20 pixels in each direction
   rect.DeflateRect(20, 20);

   // draw a thick black rectangle filled with blue
   pDC->Rectangle(rect);

   // put back the old objects
   pDC->SelectObject(pOldBrush);
   pDC->SelectObject(pOldPen);
}

CDC::RectVisible

Determines whether any part of the given rectangle lies within the clipping region of the display context.

virtual BOOL RectVisible(LPCRECT lpRect) const;  

Parameters

lpRect
Points to a RECT structure or a CRect object that contains the logical coordinates of the specified rectangle.

Return Value

Nonzero if any portion of the given rectangle lies within the clipping region; otherwise 0.

CDC::ReleaseAttribDC

Call this member function to set m_hAttribDC to NULL.

virtual void ReleaseAttribDC();

Remarks

This does not cause a Detach to occur. Only the output device context is attached to the CDC object, and only it can be detached.

CDC::ReleaseOutputDC

Call this member function to set the m_hDC member to NULL.

virtual void ReleaseOutputDC();

Remarks

This member function cannot be called when the output device context is attached to the CDC object. Use the Detach member function to detach the output device context.

CDC::ResetDC

Call this member function to update the device context wrapped by the CDC object.

BOOL ResetDC(const DEVMODE* lpDevMode);

Parameters

lpDevMode
A pointer to a Windows DEVMODE structure.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The device context is updated from the information specified in the Windows DEVMODE structure. This member function only resets the attribute device context.

An application will typically use the ResetDC member function when a window processes a WM_DEVMODECHANGE message. You can also use this member function to change the paper orientation or paper bins while printing a document.

You cannot use this member function to change the driver name, device name, or output port. When the user changes the port connection or device name, you must delete the original device context and create a new device context with the new information.

Before you call this member function, you must ensure that all objects (other than stock objects) that had been selected into the device context have been selected out.

CDC::RestoreDC

Restores the device context to the previous state identified by nSavedDC.

virtual BOOL RestoreDC(int nSavedDC);

Parameters

nSavedDC
Specifies the device context to be restored. It can be a value returned by a previous SaveDC function call. If nSavedDC is –1, the most recently saved device context is restored.

Return Value

Nonzero if the specified context was restored; otherwise 0.

Remarks

RestoreDC restores the device context by popping state information off a stack created by earlier calls to the SaveDC member function.

The stack can contain the state information for several device contexts. If the context specified by nSavedDC is not at the top of the stack, RestoreDC deletes all state information between the device context specified by nSavedDC and the top of the stack. The deleted information is lost.

CDC::RoundRect

Draws a rectangle with rounded corners using the current pen.

BOOL RoundRect(
    int x1,  
    int y1,  
    int x2,  
    int y2,  
    int x3,  
    int y3);

 
BOOL RoundRect(
    LPCRECT lpRect,
    POINT point);

Parameters

x1
Specifies the x-coordinate of the upper-left corner of the rectangle (in logical units).

y1
Specifies the y-coordinate of the upper-left corner of the rectangle (in logical units).

x2
Specifies the x-coordinate of the lower-right corner of the rectangle (in logical units).

y2
Specifies the y-coordinate of the lower-right corner of the rectangle (in logical units).

x3
Specifies the width of the ellipse used to draw the rounded corners (in logical units).

y3
Specifies the height of the ellipse used to draw the rounded corners (in logical units).

lpRect
Specifies the bounding rectangle in logical units. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

point
The x-coordinate of point specifies the width of the ellipse to draw the rounded corners (in logical units). The y-coordinate of point specifies the height of the ellipse to draw the rounded corners (in logical units). You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The interior of the rectangle is filled using the current brush.

The figure this function draws extends up to but does not include the right and bottom coordinates. This means that the height of the figure is y2y1 and the width of the figure is x2x1. Both the height and the width of the bounding rectangle must be greater than 2 units and less than 32,767 units.

Example

void CDCView::DrawRoundRect(CDC* pDC)
{
   // create and select a solid blue brush
   CBrush brushBlue(RGB(0, 0, 255));
   CBrush* pOldBrush = pDC->SelectObject(&brushBlue);

   // create and select a thick, black pen
   CPen penBlack;
   penBlack.CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
   CPen* pOldPen = pDC->SelectObject(&penBlack);

   // get our client rectangle
   CRect rect;
   GetClientRect(rect);

   // shrink our rect 20 pixels in each direction
   rect.DeflateRect(20, 20);

   // Draw a thick black rectangle filled with blue
   // corners rounded at a 17-unit radius. Note that
   // a radius of three or less is not noticable because
   // the pen is three units wide.
   pDC->RoundRect(rect, CPoint(17, 17));

   // put back the old objects
   pDC->SelectObject(pOldBrush);
   pDC->SelectObject(pOldPen);
}

CDC::SaveDC

Saves the current state of the device context by copying state information (such as clipping region, selected objects, and mapping mode) to a context stack maintained by Windows.

virtual int SaveDC();

Return Value

An integer identifying the saved device context. It is 0 if an error occurs. This return value can be used to restore the device context by calling RestoreDC.

Remarks

The saved device context can later be restored by using RestoreDC.

SaveDC can be used any number of times to save any number of device-context states.

CDC::ScaleViewportExt

Modifies the viewport extents relative to the current values.

virtual CSize ScaleViewportExt(
    int xNum,  
    int xDenom,  
    int yNum,  
    int yDenom);

Parameters

xNum
Specifies the amount by which to multiply the current x-extent.

xDenom
Specifies the amount by which to divide the result of multiplying the current x-extent by the value of the xNum parameter.

yNum
Specifies the amount by which to multiply the current y-extent.

yDenom
Specifies the amount by which to divide the result of multiplying the current y-extent by the value of the yNum parameter.

Return Value

The previous viewport extents (in device units) as a CSize object.

Remarks

The formulas are written as follows:

xNewVE = ( xOldVE * xNum ) / xDenom

yNewVE = ( yOldVE * yNum ) / yDenom

The new viewport extents are calculated by multiplying the current extents by the given numerator and then dividing by the given denominator.

CDC::ScaleWindowExt

Modifies the window extents relative to the current values.

virtual CSize ScaleWindowExt(
    int xNum,  
    int xDenom,  
    int yNum,  
    int yDenom);

Parameters

xNum
Specifies the amount by which to multiply the current x-extent.

xDenom
Specifies the amount by which to divide the result of multiplying the current x-extent by the value of the xNum parameter.

yNum
Specifies the amount by which to multiply the current y-extent.

yDenom
Specifies the amount by which to divide the result of multiplying the current y-extent by the value of the yNum parameter.

Return Value

The previous window extents (in logical units) as a CSize object.

Remarks

The formulas are written as follows:

xNewWE = ( xOldWE * xNum ) / xDenom

yNewWE = ( yOldWE * yNum ) / yDenom

The new window extents are calculated by multiplying the current extents by the given numerator and then dividing by the given denominator.

CDC::ScrollDC

Scrolls a rectangle of bits horizontally and vertically.

BOOL ScrollDC(
    int dx,  
    int dy,  
    LPCRECT lpRectScroll,  
    LPCRECT lpRectClip,  
    CRgn* pRgnUpdate,  
    LPRECT lpRectUpdate);

Parameters

dx
Specifies the number of horizontal scroll units.

dy
Specifies the number of vertical scroll units.

lpRectScroll
Points to the RECT structure or CRect object that contains the coordinates of the scrolling rectangle.

lpRectClip
Points to the RECT structure or CRect object that contains the coordinates of the clipping rectangle. When this rectangle is smaller than the original one pointed to by lpRectScroll, scrolling occurs only in the smaller rectangle.

pRgnUpdate
Identifies the region uncovered by the scrolling process. The ScrollDC function defines this region; it is not necessarily a rectangle.

lpRectUpdate
Points to the RECT structure or CRect object that receives the coordinates of the rectangle that bounds the scrolling update region. This is the largest rectangular area that requires repainting. The values in the structure or object when the function returns are in client coordinates, regardless of the mapping mode for the given device context.

Return Value

Nonzero if scrolling is executed; otherwise 0.

Remarks

If lpRectUpdate is NULL, Windows does not compute the update rectangle. If both pRgnUpdate and lpRectUpdate are NULL, Windows does not compute the update region. If pRgnUpdate is not NULL, Windows assumes that it contains a valid pointer to the region uncovered by the scrolling process (defined by the ScrollDC member function). The update region returned in lpRectUpdate can be passed to CWnd::InvalidateRgn if required.

An application should use the ScrollWindow member function of class CWnd when it is necessary to scroll the entire client area of a window. Otherwise, it should use ScrollDC.

CDC::SelectClipPath

Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode.

BOOL SelectClipPath(int nMode);

Parameters

nMode
Specifies the way to use the path. The following values are allowed:

  • RGN_AND The new clipping region includes the intersection (overlapping areas) of the current clipping region and the current path.

  • RGN_COPY The new clipping region is the current path.

  • RGN_DIFF The new clipping region includes the areas of the current clipping region, and those of the current path are excluded.

  • RGN_OR The new clipping region includes the union (combined areas) of the current clipping region and the current path.

  • RGN_XOR The new clipping region includes the union of the current clipping region and the current path, but without the overlapping areas.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The device context identified must contain a closed path.

CDC::SelectClipRgn

Selects the given region as the current clipping region for the device context.

int SelectClipRgn(CRgn* pRgn);

 
int SelectClipRgn(
    CRgn* pRgn,  
    int nMode);

Parameters

pRgn
Identifies the region to be selected.

  • For the first version of this function, if this value is NULL, the entire client area is selected and output is still clipped to the window.

  • For the second version of this function, this handle can be NULL only when the RGN_COPY mode is specified.

nMode
Specifies the operation to be performed. It must be one of the following values:

  • RGN_AND The new clipping region combines the overlapping areas of the current clipping region and the region identified by pRgn.

  • RGN_COPY The new clipping region is a copy of the region identified by pRgn. This is functionality is identical to the first version of SelectClipRgn. If the region identified by pRgn is NULL, the new clipping region becomes the default clipping region (a null region).

  • RGN_DIFF The new clipping region combines the areas of the current clipping region with those areas excluded from the region identified by pRgn.

  • RGN_OR The new clipping region combines the current clipping region and the region identified by pRgn.

  • RGN_XOR The new clipping region combines the current clipping region and the region identified by pRgn but excludes any overlapping areas.

Return Value

The region's type. It can be any of the following values:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context or region is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Remarks

Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts, or it can be deleted.

The function assumes that the coordinates for the given region are specified in device units. Some printer devices support text output at a higher resolution than graphics output in order to retain the precision needed to express text metrics. These devices report device units at the higher resolution, that is, in text units. These devices then scale coordinates for graphics so that several reported device units map to only 1 graphic unit. You should always call the SelectClipRgn function using text units.

Applications that must take the scaling of graphics objects in the GDI can use the GETSCALINGFACTOR printer escape to determine the scaling factor. This scaling factor affects clipping. If a region is used to clip graphics, GDI divides the coordinates by the scaling factor. If the region is used to clip text, GDI makes no scaling adjustment. A scaling factor of 1 causes the coordinates to be divided by 2; a scaling factor of 2 causes the coordinates to be divided by 4; and so on.

CDC::SelectObject

Selects an object into the device context.

CPen* SelectObject(CPen* pPen);  
CBrush* SelectObject(CBrush* pBrush);  
virtual CFont* SelectObject(CFont* pFont);  
CBitmap* SelectObject(CBitmap* pBitmap);  
int SelectObject(CRgn* pRgn);  
CGdiObject* SelectObject(CGdiObject* pObject);

Parameters

pPen
A pointer to a CPen object to be selected.

pBrush
A pointer to a CBrush object to be selected.

pFont
A pointer to a CFont object to be selected.

pBitmap
A pointer to a CBitmap object to be selected.

pRgn
A pointer to a CRgn object to be selected.

pObject
A pointer to a CGdiObject object to be selected.

Return Value

A pointer to the object being replaced. This is a pointer to an object of one of the classes derived from CGdiObject, such as CPen, depending on which version of the function is used. The return value is NULL if there is an error. This function may return a pointer to a temporary object. This temporary object is only valid during the processing of one Windows message. For more information, see CGdiObject::FromHandle.

The version of the member function that takes a region parameter performs the same task as the SelectClipRgn member function. Its return value can be any of the following:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context or region is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Remarks

Class CDC provides five versions specialized for particular kinds of GDI objects, including pens, brushes, fonts, bitmaps, and regions. The newly selected object replaces the previous object of the same type. For example, if pObject of the general version of SelectObject points to a CPen object, the function replaces the current pen with the pen specified by pObject.

An application can select a bitmap into memory device contexts only and into only one memory device context at a time. The format of the bitmap must either be monochrome or compatible with the device context; if it is not, SelectObject returns an error.

For Windows 3.1 and later, the SelectObject function returns the same value whether it is used in a metafile or not. Under previous versions of Windows, SelectObject returned a nonzero value for success and 0 for failure when it was used in a metafile.

CDC::SelectPalette

Selects the logical palette that is specified by pPalette as the selected palette object of the device context.

CPalette* SelectPalette(
    CPalette* pPalette,  
    BOOL bForceBackground);

Parameters

pPalette
Identifies the logical palette to be selected. This palette must already have been created with the CPalette member function CreatePalette.

bForceBackground
Specifies whether the logical palette is forced to be a background palette. If bForceBackground is nonzero, the selected palette is always a background palette, regardless of whether the window has the input focus. If bForceBackground is 0 and the device context is attached to a window, the logical palette is a foreground palette when the window has the input focus.

Return Value

A pointer to a CPalette object identifying the logical palette replaced by the palette specified by pPalette. It is NULL if there is an error.

Remarks

The new palette becomes the palette object used by GDI to control colors displayed in the device context and replaces the previous palette.

An application can select a logical palette into more than one device context. However, changes to a logical palette will affect all device contexts for which it is selected. If an application selects a palette into more than one device context, the device contexts must all belong to the same physical device.

CDC::SelectStockObject

Selects a CGdiObject object that corresponds to one of the predefined stock pens, brushes, or fonts.

virtual CGdiObject* SelectStockObject(int nIndex);

Parameters

nIndex
Specifies the kind of stock object desired. It can be one of the following values:

  • BLACK_BRUSH Black brush.

  • DKGRAY_BRUSH Dark gray brush.

  • GRAY_BRUSH Gray brush.

  • HOLLOW_BRUSH Hollow brush.

  • LTGRAY_BRUSH Light gray brush.

  • NULL_BRUSH Null brush.

  • WHITE_BRUSH White brush.

  • BLACK_PEN Black pen.

  • NULL_PEN Null pen.

  • WHITE_PEN White pen.

  • ANSI_FIXED_FONT ANSI fixed system font.

  • ANSI_VAR_FONT ANSI variable system font.

  • DEVICE_DEFAULT_FONT Device-dependent font.

  • OEM_FIXED_FONT OEM-dependent fixed font.

  • SYSTEM_FONT The system font. By default, Windows uses the system font to draw menus, dialog-box controls, and other text. It is best, however, not to rely on SYSTEM_FONT to obtain the font used by dialogs and windows. Instead, use the SystemParametersInfo function with the SPI_GETNONCLIENTMETRICS parameter to retrieve the current font. SystemParametersInfo takes into account the current theme and provides font information for captions, menus, and message dialogs.

  • SYSTEM_FIXED_FONT The fixed-width system font used in Windows prior to version 3.0. This object is available for compatibility with earlier versions of Windows.

  • DEFAULT_PALETTE Default color palette. This palette consists of the 20 static colors in the system palette.

Return Value

A pointer to the CGdiObject object that was replaced if the function is successful. The actual object pointed to is a CPen, CBrush, or CFont object. If the call is unsuccessful, the return value is NULL.

CDC::SetAbortProc

Installs the abort procedure for the print job.

int SetAbortProc(BOOL (CALLBACK* lpfn)(HDC, int));

Parameters

lpfn
A pointer to the abort function to install as the abort procedure. For more about the callback function, see Callback Function for CDC::SetAbortProc.

Return Value

Specifies the outcome of the SetAbortProc function. Some of the following values are more probable than others, but all are possible.

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User ended the job through the Print Manager.

Remarks

If an application is to allow the print job to be canceled during spooling, it must set the abort function before the print job is started with the StartDoc member function. The Print Manager calls the abort function during spooling to allow the application to cancel the print job or to process out-of-disk-space conditions. If no abort function is set, the print job will fail if there is not enough disk space for spooling.

Note that the features of Microsoft Visual C++ simplify the creation of the callback function passed to SetAbortProc. The address passed to the EnumObjects member function is a pointer to a function exported with __declspec(dllexport) and with the __stdcall calling convention.

You also do not have to export the function name in an EXPORTS statement in your application's module-definition file. You can instead use the EXPORT function modifier, as in

BOOL CALLBACK EXPORT AFunction( HDC, int);

to cause the compiler to emit the proper export record for export by name without aliasing. This works for most needs. For some special cases, such as exporting a function by ordinal or aliasing the export, you still need to use an EXPORTS statement in a module-definition file.

Callback registration interfaces are now type-safe (you must pass in a function pointer that points to the right kind of function for the specific callback).

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions.

CDC::SetArcDirection

Sets the drawing direction to be used for arc and rectangle functions.

int SetArcDirection(int nArcDirection);

Parameters

nArcDirection
Specifies the new arc direction. This parameter can be either of the following values:

  • AD_COUNTERCLOCKWISE Figures drawn counterclockwise.

  • AD_CLOCKWISE Figures drawn clockwise.

Return Value

Specifies the old arc direction, if successful; otherwise 0.

Remarks

The default direction is counterclockwise. The SetArcDirection function specifies the direction in which the following functions draw:

Arc Pie
ArcTo Rectangle
Chord RoundRect
Ellipse

CDC::SetAttribDC

Call this function to set the attribute device context, m_hAttribDC.

virtual void SetAttribDC(HDC hDC);

Parameters

hDC
A Windows device context.

Remarks

This member function does not attach the device context to the CDC object. Only the output device context is attached to a CDC object.

CDC::SetBkColor

Sets the current background color to the specified color.

virtual COLORREF SetBkColor(COLORREF crColor);

Parameters

crColor
Specifies the new background color.

Return Value

The previous background color as an RGB color value. If an error occurs, the return value is 0x80000000.

Remarks

If the background mode is OPAQUE, the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. The system also uses the background color when converting bitmaps between color and monochrome device contexts.

If the device cannot display the specified color, the system sets the background color to the nearest physical color.

CDC::SetBkMode

Sets the background mode.

int SetBkMode(int nBkMode);

Parameters

nBkMode
Specifies the mode to be set. This parameter can be either of the following values:

  • OPAQUE Background is filled with the current background color before the text, hatched brush, or pen is drawn. This is the default background mode.

  • TRANSPARENT Background is not changed before drawing.

Return Value

The previous background mode.

Remarks

The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line.

Example

See the example for CWnd::OnCtlColor.

CDC::SetBoundsRect

Controls the accumulation of bounding-rectangle information for the specified device context.

UINT SetBoundsRect(
    LPCRECT lpRectBounds,  
    UINT flags);

Parameters

lpRectBounds
Points to a RECT structure or CRect object that is used to set the bounding rectangle. Rectangle dimensions are given in logical coordinates. This parameter can be NULL.

flags
Specifies how the new rectangle will be combined with the accumulated rectangle. This parameter can be a combination of the following values:

  • DCB_ACCUMULATE Add the rectangle specified by lpRectBounds to the bounding rectangle (using a rectangle-union operation).

  • DCB_DISABLE Turn off bounds accumulation.

  • DCB_ENABLE Turn on bounds accumulation. (The default setting for bounds accumulation is disabled.)

Return Value

The current state of the bounding rectangle, if the function is successful. Like flags, the return value can be a combination of DCB_ values:

  • DCB_ACCUMULATE The bounding rectangle is not empty. This value will always be set.

  • DCB_DISABLE Bounds accumulation is off.

  • DCB_ENABLE Bounds accumulation is on.

Remarks

Windows can maintain a bounding rectangle for all drawing operations. This rectangle can be queried and reset by the application. The drawing bounds are useful for invalidating bitmap caches.

CDC::SetBrushOrg

Specifies the origin that GDI will assign to the next brush that the application selects into the device context.

CPoint SetBrushOrg(
    int x,  
    int y);  
  
CPoint SetBrushOrg(POINT point);

Parameters

x
Specifies the x-coordinate (in device units) of the new origin. This value must be in the range 0–7.

y
Specifies the y-coordinate (in device units) of the new origin. This value must be in the range 0–7.

point
Specifies the x- and y-coordinates of the new origin. Each value must be in the range 0–7. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

The previous origin of the brush in device units.

Remarks

The default coordinates for the brush origin are (0, 0). To alter the origin of a brush, call the UnrealizeObject function for the CBrush object, call SetBrushOrg, and then call the SelectObject member function to select the brush into the device context.

Do not use SetBrushOrg with stock CBrush objects.

CDC::SetColorAdjustment

Sets the color adjustment values for the device context using the specified values.

BOOL SetColorAdjustment(const COLORADJUSTMENT* lpColorAdjust);

Parameters

lpColorAdjust
Points to a COLORADJUSTMENT data structure containing the color adjustment values.

Return Value

Nonzero if successful; otherwise 0.

Remarks

The color adjustment values are used to adjust the input color of the source bitmap for calls to the CDC::StretchBlt member function when HALFTONE mode is set.

CDC::SetDCBrushColor

Sets the current device context (DC) brush color to the specified color value.

COLORREF SetDCBrushColor(COLORREF crColor);

Parameters

crColor
Specifies the new brush color.

Return Value

If the function succeeds, the return value specifies the previous DC brush color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Remarks

This method emulates the functionality of the function SetDCBrushColor, as described in the Windows SDK.

CDC::SetDCPenColor

Sets the current device context (DC) pen color to the specified color value.

COLORREF SetDCPenColor(COLORREF crColor);

Parameters

crColor
Specifies the new pen color.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This member function utilizes the Win32 function SetDCPenColor, as described in the Windows SDK.

CDC::SetGraphicsMode

Sets the graphics mode for the specified device context.

int SetGraphicsMode(int iMode);

Parameters

iMode
Specifies the graphics mode. For a list of the values that this parameter can take, see SetGraphicsMode.

Return Value

Returns the old graphics mode on success.

Returns 0 on failure. To get extended error information, call GetLastError.

Remarks

This method wraps the Windows GDI function SetGraphicsMode.

CDC::SetLayout

Call this member function to change the layout of the text and graphics for a device context to right to left, the standard layout for cultures such as Arabic and Hebrew.

DWORD SetLayout(DWORD dwLayout);

Parameters

dwLayout
Device context layout and bitmap control flags. It can be a combination of the following values.

Value Meaning
LAYOUT_BITMAPORIENTATIONPRESERVED Disables any reflection for calls to CDC::BitBlt and CDC::StretchBlt.
LAYOUT_RTL Sets the default horizontal layout to be right to left.
LAYOUT_LTR Sets the default layout to be left to right.

Return Value

If successful, the previous layout of the device context.

If unsuccessful, GDI_ERROR. To get extended error information, call GetLastError.

Remarks

Normally, you would not call SetLayout for a window. Rather, you control the right-to-left layout in a window by setting the extended window styles such as WS_EX_RTLREADING. A device context, such as a printer or a metafile, does not inherit this layout. The only way to set the device context for a right-to-left layout is by calling SetLayout.

If you call SetLayout(LAYOUT_RTL ), SetLayout automatically changes the mapping mode to MM_ISOTROPIC. As a result, a subsequent call to GetMapMode will return MM_ISOTROPIC instead of MM_TEXT.

In some cases, such as with many bitmaps, you may want to preserve the left-to-right layout. In these cases, render the image by calling BitBlt or StretchBlt, then set the bitmap control flag for dwLayout to LAYOUT_BITMAPORIENTATIONPRESERVED.

Once you change the layout with the LAYOUT_RTL flag, the flags normally specifying right or left are reversed. To avoid confusion, you may want to define alternate names for the standard flags. For a list of suggested alternate flag names, see SetLayout in the Windows SDK.

CDC::SetMapMode

Sets the mapping mode.

virtual int SetMapMode(int nMapMode);

Parameters

nMapMode
Specifies the new mapping mode. It can be any one of the following values:

  • MM_ANISOTROPIC Logical units are converted to arbitrary units with arbitrarily scaled axes. Setting the mapping mode to MM_ANISOTROPIC does not change the current window or viewport settings. To change the units, orientation, and scaling, call the SetWindowExt and SetViewportExt member functions.

  • MM_HIENGLISH Each logical unit is converted to 0.001 inch. Positive x is to the right; positive y is up.

  • MM_HIMETRIC Each logical unit is converted to 0.01 millimeter. Positive x is to the right; positive y is up.

  • MM_ISOTROPIC Logical units are converted to arbitrary units with equally scaled axes; that is, 1 unit along the x-axis is equal to 1 unit along the y-axis. Use the SetWindowExt and SetViewportExt member functions to specify the desired units and the orientation of the axes. GDI makes adjustments as necessary to ensure that the x and y units remain the same size.

  • MM_LOENGLISH Each logical unit is converted to 0.01 inch. Positive x is to the right; positive y is up.

  • MM_LOMETRIC Each logical unit is converted to 0.1 millimeter. Positive x is to the right; positive y is up.

  • MM_TEXT Each logical unit is converted to 1 device pixel. Positive x is to the right; positive y is down.

  • MM_TWIPS Each logical unit is converted to 1/20 of a point. (Because a point is 1/72 inch, a twip is 1/1440 inch.) Positive x is to the right; positive y is up.

Return Value

The previous mapping mode.

Remarks

The mapping mode defines the unit of measure used to convert logical units to device units; it also defines the orientation of the device's x- and y-axes. GDI uses the mapping mode to convert logical coordinates into the appropriate device coordinates. The MM_TEXT mode allows applications to work in device pixels, where 1 unit is equal to 1 pixel. The physical size of a pixel varies from device to device.

The MM_HIENGLISH, MM_HIMETRIC, MM_LOENGLISH, MM_LOMETRIC, and MM_TWIPS modes are useful for applications that must draw in physically meaningful units (such as inches or millimeters). The MM_ISOTROPIC mode ensures a 1:1 aspect ratio, which is useful when it is important to preserve the exact shape of an image. The MM_ANISOTROPIC mode allows the x- and y-coordinates to be adjusted independently.

Note

If you call SetLayout to change the DC (device context) to right-to-left layout, SetLayout automatically changes the mapping mode to MM_ISOTROPIC.

Example

See the example for CView::OnPrepareDC.

CDC::SetMapperFlags

Changes the method used by the font mapper when it converts a logical font to a physical font.

DWORD SetMapperFlags(DWORD dwFlag);

Parameters

dwFlag
Specifies whether the font mapper attempts to match a font's aspect height and width to the device. When this value is ASPECT_FILTERING, the mapper selects only fonts whose x-aspect and y-aspect exactly match those of the specified device.

Return Value

The previous value of the font-mapper flag.

Remarks

An application can use SetMapperFlags to cause the font mapper to attempt to choose only a physical font that exactly matches the aspect ratio of the specified device.

An application that uses only raster fonts can use the SetMapperFlags function to ensure that the font selected by the font mapper is attractive and readable on the specified device. Applications that use scalable (TrueType) fonts typically do not use SetMapperFlags.

If no physical font has an aspect ratio that matches the specification in the logical font, GDI chooses a new aspect ratio and selects a font that matches this new aspect ratio.

CDC::SetMiterLimit

Sets the limit for the length of miter joins for the device context.

BOOL SetMiterLimit(float fMiterLimit);

Parameters

fMiterLimit
Specifies the new miter limit for the device context.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The miter length is defined as the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls on the outside of the join. The miter limit is the maximum allowed ratio of the miter length to the line width. The default miter limit is 10.0.

CDC::SetOutputDC

Call this member function to set the output device context, m_hDC.

virtual void SetOutputDC(HDC hDC);

Parameters

hDC
A Windows device context.

Remarks

This member function can only be called when a device context has not been attached to the CDC object. This member function sets m_hDC but does not attach the device context to the CDC object.

CDC::SetPixel

Sets the pixel at the point specified to the closest approximation of the color specified by crColor.

COLORREF SetPixel(
    int x,  
    int y,  
    COLORREF crColor);

 
COLORREF SetPixel(
    POINT point,  
    COLORREF crColor);

Parameters

x
Specifies the logical x-coordinate of the point to be set.

y
Specifies the logical y-coordinate of the point to be set.

crColor
A COLORREF RGB value that specifies the color used to paint the point. See COLORREF in the Windows SDK for a description of this value.

point
Specifies the logical x- and y-coordinates of the point to be set. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

An RGB value for the color that the point is actually painted. This value can be different from that specified by crColor if an approximation of that color is used. If the function fails (if the point is outside the clipping region), the return value is –1.

Remarks

The point must be in the clipping region. If the point is not in the clipping region, the function does nothing.

Not all devices support the SetPixel function. To determine whether a device supports SetPixel, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_BITBLT flag.

CDC::SetPixelV

Sets the pixel at the specified coordinates to the closest approximation of the specified color.

BOOL SetPixelV(
    int x,  
    int y,  
    COLORREF crColor);

 
BOOL SetPixelV(
    POINT point,  
    COLORREF crColor);

Parameters

x
Specifies the x-coordinate, in logical units, of the point to be set.

y
Specifies the y-coordinate, in logical units, of the point to be set.

crColor
Specifies the color to be used to paint the point.

point
Specifies the logical x- and y-coordinates of the point to be set. You can pass either a POINT data structure or a CPoint object for this parameter.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The point must be in both the clipping region and the visible part of the device surface. Not all devices support the member function. For more information, see the RC_BITBLT capability in the CDC::GetDeviceCaps member function. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.

CDC::SetPolyFillMode

Sets the polygon-filling mode.

int SetPolyFillMode(int nPolyFillMode);

Parameters

nPolyFillMode
Specifies the new filling mode. This value may be either ALTERNATE or WINDING. The default mode set in Windows is ALTERNATE.

Return Value

The previous filling mode, if successful; otherwise 0.

Remarks

When the polygon-filling mode is ALTERNATE, the system fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, the system fills the area between the first and second side, between the third and fourth side, and so on. This mode is the default.

When the polygon-filling mode is WINDING, the system uses the direction in which a figure was drawn to determine whether to fill an area. Each line segment in a polygon is drawn in either a clockwise or a counterclockwise direction. Whenever an imaginary line drawn from an enclosed area to the outside of a figure passes through a clockwise line segment, a count is incremented. When the line passes through a counterclockwise line segment, the count is decremented. The area is filled if the count is nonzero when the line reaches the outside of the figure.

CDC::SetROP2

Sets the current drawing mode.

int SetROP2(int nDrawMode);

Parameters

nDrawMode
Specifies the new drawing mode. It can be any of the following values:

  • R2_BLACK Pixel is always black.

  • R2_WHITE Pixel is always white.

  • R2_NOP Pixel remains unchanged.

  • R2_NOT Pixel is the inverse of the screen color.

  • R2_COPYPEN Pixel is the pen color.

  • R2_NOTCOPYPEN Pixel is the inverse of the pen color.

  • R2_MERGEPENNOT Pixel is a combination of the pen color and the inverse of the screen color (final pixel = (NOT screen pixel) OR pen).

  • R2_MASKPENNOT Pixel is a combination of the colors common to both the pen and the inverse of the screen (final pixel = (NOT screen pixel) AND pen).

  • R2_MERGENOTPEN Pixel is a combination of the screen color and the inverse of the pen color (final pixel = (NOT pen) OR screen pixel).

  • R2_MASKNOTPEN Pixel is a combination of the colors common to both the screen and the inverse of the pen (final pixel = (NOT pen) AND screen pixel).

  • R2_MERGEPEN Pixel is a combination of the pen color and the screen color (final pixel = pen OR screen pixel).

  • R2_NOTMERGEPEN Pixel is the inverse of the R2_MERGEPEN color (final pixel = NOT(pen OR screen pixel)).

  • R2_MASKPEN Pixel is a combination of the colors common to both the pen and the screen (final pixel = pen AND screen pixel).

  • R2_NOTMASKPEN Pixel is the inverse of the R2_MASKPEN color (final pixel = NOT(pen AND screen pixel)).

  • R2_XORPEN Pixel is a combination of the colors that are in the pen or in the screen, but not in both (final pixel = pen XOR screen pixel).

  • R2_NOTXORPEN Pixel is the inverse of the R2_XORPEN color (final pixel = NOT(pen XOR screen pixel)).

Return Value

The previous drawing mode.

It can be any of the values given in the Windows SDK.

Remarks

The drawing mode specifies how the colors of the pen and the interior of filled objects are combined with the color already on the display surface.

The drawing mode is for raster devices only; it does not apply to vector devices. Drawing modes are binary raster-operation codes representing all possible Boolean combinations of two variables, using the binary operators AND, OR, and XOR (exclusive OR), and the unary operation NOT.

CDC::SetStretchBltMode

Sets the bitmap-stretching mode for the StretchBlt member function.

int SetStretchBltMode(int nStretchMode);

Parameters

nStretchMode
Specifies the stretching mode. It can be any of the following values:

Value Description
BLACKONWHITE Performs a Boolean AND operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves black pixels at the expense of white pixels.
COLORONCOLOR Deletes the pixels. This mode deletes all eliminated lines of pixels without trying to preserve their information.
HALFTONE Maps pixels from the source rectangle into blocks of pixels in the destination rectangle. The average color over the destination block of pixels approximates the color of the source pixels.
After setting the HALFTONE stretching mode, an application must call the Win32 function SetBrushOrgEx to set the brush origin. If it fails to do so, brush misalignment occurs.
STRETCH_ANDSCANS Windows 95/98: Same as BLACKONWHITE
STRETCH_DELETESCANS Windows 95/98: Same as COLORONCOLOR
STRETCH_HALFTONE Windows 95/98: Same as HALFTONE.
STRETCH_ORSCANS Windows 95/98: Same as WHITEONBLACK
WHITEONBLACK Performs a Boolean OR operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves white pixels at the expense of black pixels.

Return Value

The previous stretching mode. It can be STRETCH_ANDSCANS, STRETCH_DELETESCANS, or STRETCH_ORSCANS.

Remarks

The bitmap-stretching mode defines how information is removed from bitmaps that are compressed by using the function.

The BLACKONWHITE ( STRETCH_ANDSCANS) and WHITEONBLACK ( STRETCH_ORSCANS) modes are typically used to preserve foreground pixels in monochrome bitmaps. The COLORONCOLOR ( STRETCH_DELETESCANS) mode is typically used to preserve color in color bitmaps.

The HALFTONE mode requires more processing of the source image than the other three modes; it is slower than the others, but produces higher quality images. Also note that SetBrushOrgEx must be called after setting the HALFTONE mode to avoid brush misalignment.

Additional stretching modes might also be available depending on the capabilities of the device driver.

CDC::SetTextAlign

Sets the text-alignment flags.

UINT SetTextAlign(UINT nFlags);

Parameters

nFlags
Specifies text-alignment flags. The flags specify the relationship between a point and a rectangle that bounds the text. The point can be either the current position or coordinates specified by a text-output function. The rectangle that bounds the text is defined by the adjacent character cells in the text string. The nFlags parameter can be one or more flags from the following three categories. Choose only one flag from each category. The first category affects text alignment in the x-direction:

  • TA_CENTER Aligns the point with the horizontal center of the bounding rectangle.

  • TA_LEFT Aligns the point with the left side of the bounding rectangle. This is the default setting.

  • TA_RIGHT Aligns the point with the right side of the bounding rectangle.

The second category affects text alignment in the y-direction:

  • TA_BASELINE Aligns the point with the base line of the chosen font.

  • TA_BOTTOM Aligns the point with the bottom of the bounding rectangle.

  • TA_TOP Aligns the point with the top of the bounding rectangle. This is the default setting.

The third category determines whether the current position is updated when text is written:

  • TA_NOUPDATECP Does not update the current position after each call to a text-output function. This is the default setting.

  • TA_UPDATECP Updates the current x-position after each call to a text-output function. The new position is at the right side of the bounding rectangle for the text. When this flag is set, the coordinates specified in calls to the TextOut member function are ignored.

Return Value

The previous text-alignment setting, if successful. The low-order byte contains the horizontal setting and the high-order byte contains the vertical setting; otherwise 0.

Remarks

The TextOut and ExtTextOut member functions use these flags when positioning a string of text on a display or device. The flags specify the relationship between a specific point and a rectangle that bounds the text. The coordinates of this point are passed as parameters to the TextOut member function. The rectangle that bounds the text is formed by the adjacent character cells in the text string.

CDC::SetTextCharacterExtra

Sets the amount of intercharacter spacing.

int SetTextCharacterExtra(int nCharExtra);

Parameters

nCharExtra
Specifies the amount of extra space (in logical units) to be added to each character. If the current mapping mode is not MM_TEXT, nCharExtra is transformed and rounded to the nearest pixel.

Return Value

The amount of the previous intercharacter spacing.

Remarks

GDI adds this spacing to each character, including break characters, when it writes a line of text to the device context. The default value for the amount of intercharacter spacing is 0.

CDC::SetTextColor

Sets the text color to the specified color.

virtual COLORREF SetTextColor(COLORREF crColor);

Parameters

crColor
Specifies the color of the text as an RGB color value.

Return Value

An RGB value for the previous text color.

Remarks

The system will use this text color when writing text to this device context and also when converting bitmaps between color and monochrome device contexts.

If the device cannot represent the specified color, the system sets the text color to the nearest physical color. The background color for a character is specified by the SetBkColor and SetBkMode member functions.

Example

See the example for CWnd::OnCtlColor.

CDC::SetTextJustification

Adds space to the break characters in a string.

int SetTextJustification(
    int nBreakExtra,  
    int nBreakCount);

Parameters

nBreakExtra
Specifies the total extra space to be added to the line of text (in logical units). If the current mapping mode is not MM_TEXT, the value given by this parameter is converted to the current mapping mode and rounded to the nearest device unit.

nBreakCount
Specifies the number of break characters in the line.

Return Value

One if the function is successful; otherwise 0.

Remarks

An application can use the GetTextMetrics member functions to retrieve a font's break character.

After the SetTextJustification member function is called, a call to a text-output function (such as TextOut) distributes the specified extra space evenly among the specified number of break characters. The break character is usually the space character (ASCII 32), but may be defined by a font as some other character.

The member function GetTextExtent is typically used with SetTextJustification. GetTextExtent computes the width of a given line before alignment. An application can determine how much space to specify in the nBreakExtra parameter by subtracting the value returned by GetTextExtent from the width of the string after alignment.

The SetTextJustification function can be used to align a line that contains multiple runs in different fonts. In this case, the line must be created piecemeal by aligning and writing each run separately.

Because rounding errors can occur during alignment, the system keeps a running error term that defines the current error. When aligning a line that contains multiple runs, GetTextExtent automatically uses this error term when it computes the extent of the next run. This allows the text-output function to blend the error into the new run.

After each line has been aligned, this error term must be cleared to prevent it from being incorporated into the next line. The term can be cleared by calling SetTextJustification with nBreakExtra set to 0.

CDC::SetViewportExt

Sets the x- and y-extents of the viewport of the device context.

virtual CSize SetViewportExt(
    int cx,  
    int cy);  
  
CSize SetViewportExt(SIZE size);

Parameters

cx
Specifies the x-extent of the viewport (in device units).

cy
Specifies the y-extent of the viewport (in device units).

size
Specifies the x- and y-extents of the viewport (in device units).

Return Value

The previous extents of the viewport as a CSize object. When an error occurs, the x- and y-coordinates of the returned CSize object are both set to 0.

Remarks

The viewport, along with the device-context window, defines how GDI maps points in the logical coordinate system to points in the coordinate system of the actual device. In other words, they define how GDI converts logical coordinates into device coordinates.

When the following mapping modes are set, calls to SetWindowExt and SetViewportExt are ignored:

MM_HIENGLISH MM_LOMETRIC
MM_HIMETRIC MM_TEXT
MM_LOENGLISH MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExt member function before it calls SetViewportExt.

Example

See the example for CView::OnPrepareDC.

CDC::SetViewportOrg

Sets the viewport origin of the device context.

virtual CPoint SetViewportOrg(
    int x,  
    int y);  
  
CPoint SetViewportOrg(POINT point);

Parameters

x
Specifies the x-coordinate (in device units) of the origin of the viewport. The value must be within the range of the device coordinate system.

y
Specifies the y-coordinate (in device units) of the origin of the viewport. The value must be within the range of the device coordinate system.

point
Specifies the origin of the viewport. The values must be within the range of the device coordinate system. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

The previous origin of the viewport (in device coordinates) as a CPoint object.

Remarks

The viewport, along with the device-context window, defines how GDI maps points in the logical coordinate system to points in the coordinate system of the actual device. In other words, they define how GDI converts logical coordinates into device coordinates.

The viewport origin marks the point in the device coordinate system to which GDI maps the window origin, a point in the logical coordinate system specified by the SetWindowOrg member function. GDI maps all other points by following the same process required to map the window origin to the viewport origin. For example, all points in a circle around the point at the window origin will be in a circle around the point at the viewport origin. Similarly, all points in a line that passes through the window origin will be in a line that passes through the viewport origin.

Example

See the example for CView::OnPrepareDC.

CDC::SetWindowExt

Sets the x- and y-extents of the window associated with the device context.

virtual CSize SetWindowExt(
    int cx,  
    int cy);  
  
CSize SetWindowExt(SIZE size);

Parameters

cx
Specifies the x-extent (in logical units) of the window.

cy
Specifies the y-extent (in logical units) of the window.

size
Specifies the x- and y-extents (in logical units) of the window.

Return Value

The previous extents of the window (in logical units) as a CSize object. If an error occurs, the x- and y-coordinates of the returned CSize object are both set to 0.

Remarks

The window, along with the device-context viewport, defines how GDI maps points in the logical coordinate system to points in the device coordinate system.

When the following mapping modes are set, calls to SetWindowExt and SetViewportExt functions are ignored:

  • MM_HIENGLISH

  • MM_HIMETRIC

  • MM_LOENGLISH

  • MM_LOMETRIC

  • MM_TEXT

  • MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExt member function before calling SetViewportExt.

Example

See the example for CView::OnPrepareDC.

CDC::SetWindowOrg

Sets the window origin of the device context.

CPoint SetWindowOrg(
    int x,  
    int y);  
  
CPoint SetWindowOrg(POINT point);

Parameters

x
Specifies the logical x-coordinate of the new origin of the window.

y
Specifies the logical y-coordinate of the new origin of the window.

point
Specifies the logical coordinates of the new origin of the window. You can pass either a POINT structure or a CPoint object for this parameter.

Return Value

The previous origin of the window as a CPoint object.

Remarks

The window, along with the device-context viewport, defines how GDI maps points in the logical coordinate system to points in the device coordinate system.

The window origin marks the point in the logical coordinate system from which GDI maps the viewport origin, a point in the device coordinate system specified by the SetWindowOrg function. GDI maps all other points by following the same process required to map the window origin to the viewport origin. For example, all points in a circle around the point at the window origin will be in a circle around the point at the viewport origin. Similarly, all points in a line that passes through the window origin will be in a line that passes through the viewport origin.

CDC::SetWorldTransform

Sets a two-dimensional linear transformation between world space and page space for the specified device context. This transformation can be used to scale, rotate, shear, or translate graphics output.

BOOL SetWorldTransform(const XFORM& rXform);

Parameters

rXform
Reference to an XFORM structure that contains the transformation data.

Return Value

Returns a nonzero value on success.

Returns 0 on failure.

To get extended error information, call GetLastError.

Remarks

This method wraps the Windows GDI function SetWorldTransform.

CDC::StartDoc

Informs the device driver that a new print job is starting and that all subsequent StartPage and EndPage calls should be spooled under the same job until an EndDoc call occurs.

int StartDoc(LPDOCINFO lpDocInfo);  
int StartDoc(LPCTSTR lpszDocName);

Parameters

lpDocInfo
Points to a DOCINFO structure containing the name of the document file and the name of the output file.

lpszDocName
Pointer to a string containing the name of the document file.

Return Value

If the function succeeds, the return value is greater than zero. This value is the print job identifier for the document.

If the function fails, the return value is less than or equal to zero.

Remarks

This ensures that documents longer than one page will not be interspersed with other jobs.

For Windows versions 3.1 and later, this function replaces the STARTDOC printer escape. Using this function ensures that documents containing more than one page are not interspersed with other print jobs.

StartDoc should not be used inside metafiles.

Example

This code fragment gets the default printer, opens a print job, and spools one page with "Hello, World!" on it. Because the text printed by this code isn't scaled to the printer's logical units, the output text may be in such small letters that the result is unreadable. The CDC scaling functions, such as SetMapMode, SetViewportOrg, and SetWindowExt, can be used to fix the scaling.

void CDCView::DoStartDoc()
{
   // get the default printer
   CPrintDialog dlg(FALSE);
   dlg.GetDefaults();

   // is a default printer set up?
   HDC hdcPrinter = dlg.GetPrinterDC();
   if (hdcPrinter == NULL)
   {
      MessageBox(_T("Buy a printer!"));
   }
   else
   {
      // create a CDC and attach it to the default printer
      CDC dcPrinter;
      dcPrinter.Attach(hdcPrinter);

      // call StartDoc() to begin printing
      DOCINFO docinfo;
      memset(&docinfo, 0, sizeof(docinfo));
      docinfo.cbSize = sizeof(docinfo);
      docinfo.lpszDocName = _T("CDC::StartDoc() Code Fragment");

      // if it fails, complain and exit gracefully
      if (dcPrinter.StartDoc(&docinfo) < 0)
      {
        MessageBox(_T("Printer wouldn't initalize"));
      }
      else
      {
        // start a page
        if (dcPrinter.StartPage() < 0)
        {
          MessageBox(_T("Could not start page"));
          dcPrinter.AbortDoc();
        }
        else
        {
          // actually do some printing
          CGdiObject* pOldFont = dcPrinter.SelectStockObject(SYSTEM_FONT);

          dcPrinter.TextOut(50, 50, _T("Hello World!"), 12);

          dcPrinter.EndPage();
          dcPrinter.EndDoc();
          dcPrinter.SelectObject(pOldFont);
        }
      }
   }
}

CDC::StartPage

Call this member function to prepare the printer driver to receive data.

int StartPage();

Return Value

Greater than or equal to 0 if the function is successful, or a negative value if an error occurred.

Remarks

StartPage supersedes the NEWFRAME and BANDINFO escapes.

For an overview of the sequence of printing calls, see the StartDoc member function.

The system disables the ResetDC member function between calls to StartPage and EndPage.

Example

See the example for CDC::StartDoc.

CDC::StretchBlt

Copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle.

BOOL StretchBlt(
    int x,  
    int y,  
    int nWidth,  
    int nHeight,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    int nSrcWidth,  
    int nSrcHeight,  
    DWORD dwRop);

Parameters

x
Specifies the x-coordinate (in logical units) of the upper-left corner of the destination rectangle.

y
Specifies the y-coordinate (in logical units) of the upper-left corner of the destination rectangle.

nWidth
Specifies the width (in logical units) of the destination rectangle.

nHeight
Specifies the height (in logical units) of the destination rectangle.

pSrcDC
Specifies the source device context.

xSrc
Specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle.

ySrc
Specifies the y-coordinate (in logical units) of the upper-left corner of the source rectangle.

nSrcWidth
Specifies the width (in logical units) of the source rectangle.

nSrcHeight
Specifies the height (in logical units) of the source rectangle.

dwRop
Specifies the raster operation to be performed. Raster operation codes define how GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. This parameter may be one of the following values:

  • BLACKNESS Turns all output black.

  • DSTINVERT Inverts the destination bitmap.

  • MERGECOPY Combines the pattern and the source bitmap using the Boolean AND operator.

  • MERGEPAINT Combines the inverted source bitmap with the destination bitmap using the Boolean OR operator.

  • NOTSRCCOPY Copies the inverted source bitmap to the destination.

  • NOTSRCERASE Inverts the result of combining the destination and source bitmaps using the Boolean OR operator.

  • PATCOPY Copies the pattern to the destination bitmap.

  • PATINVERT Combines the destination bitmap with the pattern using the Boolean XOR operator.

  • PATPAINT Combines the inverted source bitmap with the pattern using the Boolean OR operator. Combines the result of this operation with the destination bitmap using the Boolean OR operator.

  • SRCAND Combines pixels of the destination and source bitmaps using the Boolean AND operator.

  • SRCCOPY Copies the source bitmap to the destination bitmap.

  • SRCERASE Inverts the destination bitmap and combines the result with the source bitmap using the Boolean AND operator.

  • SRCINVERT Combines pixels of the destination and source bitmaps using the Boolean XOR operator.

  • SRCPAINT Combines pixels of the destination and source bitmaps using the Boolean OR operator.

  • WHITENESS Turns all output white.

Return Value

Nonzero if the bitmap is drawn; otherwise 0.

Remarks

The function uses the stretching mode of the destination device context (set by SetStretchBltMode) to determine how to stretch or compress the bitmap.

The StretchBlt function moves the bitmap from the source device given by pSrcDC to the destination device represented by the device-context object whose member function is being called. The xSrc, ySrc, nSrcWidth, and nSrcHeight parameters define the upper-left corner and dimensions of the source rectangle. The x, y, nWidth, and nHeight parameters give the upper-left corner and dimensions of the destination rectangle. The raster operation specified by dwRop defines how the source bitmap and the bits already on the destination device are combined.

The StretchBlt function creates a mirror image of a bitmap if the signs of the nSrcWidth and nWidth or nSrcHeight and nHeight parameters differ. If nSrcWidth and nWidth have different signs, the function creates a mirror image of the bitmap along the x-axis. If nSrcHeight and nHeight have different signs, the function creates a mirror image of the bitmap along the y-axis.

The StretchBlt function stretches or compresses the source bitmap in memory and then copies the result to the destination. If a pattern is to be merged with the result, it is not merged until the stretched source bitmap is copied to the destination. If a brush is used, it is the selected brush in the destination device context. The destination coordinates are transformed according to the destination device context; the source coordinates are transformed according to the source device context.

If the destination, source, and pattern bitmaps do not have the same color format, StretchBlt converts the source and pattern bitmaps to match the destination bitmaps. The foreground and background colors of the destination device context are used in the conversion.

If StretchBlt must convert a monochrome bitmap to color, it sets white bits (1) to the background color and black bits (0) to the foreground color. To convert color to monochrome, it sets pixels that match the background color to white (1) and sets all other pixels to black (0). The foreground and background colors of the device context with color are used.

Not all devices support the StretchBlt function. To determine whether a device supports StretchBlt, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_STRETCHBLT flag.

CDC::StrokeAndFillPath

Closes any open figures in a path, strokes the outline of the path by using the current pen, and fills its interior by using the current brush.

BOOL StrokeAndFillPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The device context must contain a closed path. The StrokeAndFillPath member function has the same effect as closing all the open figures in the path, and stroking and filling the path separately, except that the filled region will not overlap the stroked region even if the pen is wide.

CDC::StrokePath

Renders the specified path by using the current pen.

BOOL StrokePath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The device context must contain a closed path.

CDC::TabbedTextOut

Call this member function to write a character string at the specified location, expanding tabs to the values specified in the array of tab-stop positions.

virtual CSize TabbedTextOut(
    int x,  
    int y,  
    LPCTSTR lpszString,  
    int nCount,  
    int nTabPositions,  
    LPINT lpnTabStopPositions,  
    int nTabOrigin);

 
CSize TabbedTextOut(
    int x,  
    int y,  
    const CString& str,  
    int nTabPositions,  
    LPINT lpnTabStopPositions,  
    int nTabOrigin);

Parameters

x
Specifies the logical x-coordinate of the starting point of the string.

y
Specifies the logical y-coordinate of the starting point of the string.

lpszString
Points to the character string to draw. You can pass either a pointer to an array of characters or a CString object for this parameter.

nCount
Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions
Specifies the number of values in the array of tab-stop positions.

lpnTabStopPositions
Points to an array containing the tab-stop positions (in logical units). The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array.

nTabOrigin
Specifies the x-coordinate of the starting position from which tabs are expanded (in logical units).

str
A CString object that contains the specified characters.

Return Value

The dimensions of the string (in logical units) as a CSize object.

Remarks

Text is written in the currently selected font. If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight times the average character width.

If nTabPositions is 1, the tab stops are separated by the distance specified by the first value in the lpnTabStopPositions array. If the lpnTabStopPositions array contains more than one value, a tab stop is set for each value in the array, up to the number specified by nTabPositions. The nTabOrigin parameter allows an application to call the TabbedTextOut function several times for a single line. If the application calls the function more than once with the nTabOrigin set to the same value each time, the function expands all tabs relative to the position specified by nTabOrigin.

By default, the current position is not used or updated by the function. If an application needs to update the current position when it calls the function, the application can call the SetTextAlign member function with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to TabbedTextOut, using the current position instead.

CDC::TextOut

Writes a character string at the specified location using the currently selected font.

virtual BOOL TextOut(
    int x,  
    int y,  
    LPCTSTR lpszString,  
    int nCount);

 
BOOL TextOut(
    int x,
    int y,
    const CString& str);

Parameters

x
Specifies the logical x-coordinate of the starting point of the text.

y
Specifies the logical y-coordinate of the starting point of the text.

lpszString
Points to the character string to be drawn.

nCount
Specifies the number of characters in the string.

str
A CString object that contains the characters to be drawn.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Character origins are at the upper-left corner of the character cell. By default, the current position is not used or updated by the function.

If an application needs to update the current position when it calls TextOut, the application can call the SetTextAlign member function with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to TextOut, using the current position instead.

Example

See the example for CDC::BeginPath.

CDC::TransparentBlt

Call this member function to transfer a bit-block of the color data, which corresponds to a rectangle of pixels from the specified source device context, into a destination device context.

BOOL TransparentBlt(
    int xDest,  
    int yDest,
    int nDestWidth,
    int nDestHeight,  
    CDC* pSrcDC,  
    int xSrc,  
    int ySrc,  
    int nSrcWidth,  
    int nSrcHeight,  
    UINT clrTransparent);

Parameters

xDest
Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.

yDest
Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.

nDestWidth
Specifies the width, in logical units, of the destination rectangle.

nDestHeight
Specifies the height, in logical units, of the destination rectangle.

pSrcDC
Pointer to the source device context.

xSrc
Specifies the x-coordinate, in logical units, of the source rectangle.

ySrc
Specifies the y-coordinate, in logical units, of the source rectangle.

nSrcWidth
Specifies the width, in logical units, of the source rectangle.

nSrcHeight
Specifies the height, in logical units, of the source rectangle.

clrTransparent
The RGB color in the source bitmap to treat as transparent.

Return Value

TRUE if successful; otherwise FALSE.

Remarks

TransparentBlt allows for transparency; that is, the RGB color indicated by clrTransparent is rendered transparent for the transfer.

For more information, see TransparentBlt in the Windows SDK.

CDC::UpdateColors

Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis.

void UpdateColors();

Remarks

An inactive window with a realized logical palette may call UpdateColors as an alternative to redrawing its client area when the system palette changes.

For more information about using color palettes, see UpdateColors in the Windows SDK.

The UpdateColors member function typically updates a client area faster than redrawing the area. However, because the function performs the color translation based on the color of each pixel before the system palette changed, each call to this function results in the loss of some color accuracy.

CDC::WidenPath

Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context.

BOOL WidenPath();

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

This function is successful only if the current pen is a geometric pen created by the second version of CreatePen member function, or if the pen is created with the first version of CreatePen and has a width, in device units, of greater than 1. The device context must contain a closed path. Any Bzier curves in the path are converted to sequences of straight lines approximating the widened curves. As such, no Bzier curves remain in the path after WidenPath is called.

See Also

CObject Class
Hierarchy Chart
CPaintDC Class
CWindowDC Class
CClientDC Class
CMetaFileDC Class