Windows GDI

Purpose

The Microsoft® Windows® graphics device interface (GDI) is the portion of the Win32® API that enables applications to use graphics and formatted text on both the video display and the printer. Win32-based applications do not access the graphics hardware directly. Instead, GDI interacts with device drivers on behalf of applications.

Where Applicable

GDI can be used in all Windows-based applications.

Developer Audience

The Win32 API is designed for use by C/C++ programmers. Familiarity with the Windows graphical user interface and message-driven architecture is required.

Run-time Requirements

Applications that use the Win32 API require Windows NT®, Windows 2000, Whistler, or Windows 95/98/Me. For information on which operating systems are required to use a particular function, see the Requirements section of the documentation for the function.

See Also

DirectX

Image Color Management (ICM)

OpenGL

Windows Multimedia

Overview

General information about GDI.

Reference

Documentation of Win32 functions and messages.

Feedback

Make error reports and feature requests directly to Microsoft.

Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


Bitmaps

A bitmap is a graphical object used to create, manipulate (scale, scroll, rotate, and paint), and store images as files on a disk. This overview describes the bitmap classes and bitmap operations.

  • About Bitmaps
  • Using Bitmaps
  • Bitmap Reference


About Bitmaps

A bitmap is one of the GDI objects that can be selected into a device context (DC). Device contexts are structures that define a set of graphic objects and their associated attributes, and graphic modes that affect output. The table below describes the GDI objects that can be selected into a device context.

Graphic object | Description
Bitmaps | Creates, manipulates (scale, scroll, rotate, and paint), and stores images as files on a disk.
Brushes | Paints the interior of polygons, ellipses, and paths.
Fonts | Draws text on video displays and other output devices.
Logical Palette | A color palette created by an application and associated with a given device context.
Paths | One or more figures (or shapes) that are filled and/or outlined.
Pens | A graphics tool that a Win32®-based application uses to draw lines and curves.
Regions | A rectangle, polygon, or ellipse (or a combination of two or more of these shapes) that can be filled, painted, inverted, framed, and used to perform hit testing (testing for the cursor location).

From a developer's perspective, a bitmap consists of a collection of structures that specify or contain the following elements:

  • A header that describes the resolution of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits, and so on.
  • A logical palette.
  • An array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette.

A bitmap size is related to the type of image it contains. Bitmap images can be either monochrome or color. In an image, each pixel corresponds to one or more bits in a bitmap. Monochrome images have a ratio of 1 bit per pixel (bpp). Color imaging is more complex. The number of colors that can be displayed by a bitmap is equal to two raised to the number of bits per pixel. Thus, a 256-color bitmap requires 8 bpp (2^8 = 256).

Control Panel applications are examples of applications that use bitmaps. When you select a wallpaper for your desktop, you actually select a bitmap, which the system uses to paint the desktop background. The system creates the selected wallpaper pattern by repeatedly drawing a 32-by-32 pixel pattern on the desktop.

The following illustration presents the developer's perspective of the bitmap found in the file Redbrick.bmp. It shows a palette array, a 32-by-32 pixel rectangle, and the index array that maps colors from the palette to pixels in the rectangle.

In the preceding example, the rectangle of pixels was created on a VGA display device using a palette of 16 colors. A 16-color palette requires 4-bit indexes; therefore, the array that maps palette colors to pixel colors is composed of 4-bit indexes as well. (For more information about logical color-palettes, see Colors.)

Note In the above bitmap, the system maps indexes to pixels beginning with the bottom scan line of the rectangular region and ending with the top scan line. A scan line is a single row of adjacent pixels on a video display. For example, the first row of the array (row 0) corresponds to the bottom row of pixels, scan line 31. This is because the above bitmap is a bottom-up device-independent bitmap (DIB), a common type of bitmap. In top-down DIBs and in device-dependent bitmaps (DDB), the system maps indexes to pixels beginning with the top scan line.


Bitmap Classifications

There are two classes of bitmaps:

  • Device-independent bitmaps (DIB). The DIB file format was designed to ensure that bitmapped graphics created using one application can be loaded and displayed in another application, retaining the same appearance as the original.
  • Device-dependent bitmaps (DDB), also known as GDI bitmaps, were the only bitmaps available in early versions of 16-bit Microsoft® Windows® (prior to version 3.0). However, as display technology improved and as the variety of available display devices increased, certain inherent problems surfaced which could only be solved using DIBs. For example, there was no method of storing (or retrieving) the resolution of the display type on which a bitmap was created, so a drawing application could not quickly determine whether a bitmap was suitable for the type of video display device on which the application was running.


Device-Independent Bitmaps

A device-independent bitmap (DIB) contains a color table. A color table describes how pixel values correspond to RGB color values, which describe colors that are produced by emitting light. Thus, a DIB can achieve the proper color scheme on any device. A DIB contains the following color and dimension information:

  • The color format of the device on which the rectangular image was created.
  • The resolution of the device on which the rectangular image was created.
  • The palette for the device on which the image was created.
  • An array of bits that maps red, green, blue (RGB) triplets to pixels in the rectangular image.
  • A data-compression identifier that indicates the data compression scheme (if any) used to reduce the size of the array of bits.

The color and dimension information is stored in a BITMAPINFO structure, which consists of a BITMAPINFOHEADER structure followed by two or more RGBQUAD structures. The BITMAPINFOHEADER structure specifies the dimensions of the pixel rectangle, describes the device's color technology, and identifies the compression schemes used to reduce the bitmap's size. The RGBQUAD structures identify the colors that appear in the pixel rectangle.

There are two varieties of DIBs:

  • A bottom-up DIB, in which the origin lies at the lower-left corner.
  • A top-down DIB, in which the origin lies at the upper-left corner.

If the height of a DIB, as indicated by the Height member of the bitmap information header structure, is a positive value, it is a bottom-up DIB; if the height is a negative value, it is a top-down DIB. Top-down DIBs cannot be compressed.

The color format is specified in terms of a count of color planes and color bits. The count of color planes is always 1; the count of color bits is 1 for monochrome bitmaps, 4 for VGA bitmaps, and 8, 16, 24, or 32 for bitmaps on other color devices. An application retrieves the number of color bits that a particular display (or printer) uses by calling the GetDeviceCaps function, specifying BITSPIXEL as the second argument.

The resolution of a display device is specified in pixels-per-meter. An application can retrieve the horizontal resolution for a video display, or printer, by following this three-step process.

  1. Call the GetDeviceCaps function, specifying HORZRES as the second argument.
  2. Call GetDeviceCaps a second time, specifying HORZSIZE as the second argument.
  3. Divide the first return value by the second return value.

The application can retrieve the vertical resolution by using the same three-step process with different parameters: VERTRES in place of HORZRES, and VERTSIZE in place of HORZSIZE.

The palette is represented by an array of RGBQUAD structures that specify the red, green, and blue intensity components for each color in a display device's color palette. Each color index in the palette array maps to a specific pixel in the rectangular region associated with the bitmap. The size of this array, in bits, is equivalent to the width of the rectangle, in pixels, multiplied by the height of the rectangle, in pixels, multiplied by the count of color bits for the device. An application can retrieve the size of the device's palette by calling the GetDeviceCaps function, specifying the NUMCOLORS constant as the second argument.

The Microsoft® Win32® API supports the compression of the palette array for 8-bpp and 4-bpp bottom-up DIBs. These arrays can be compressed by using the run-length encoding (RLE) scheme. The RLE scheme uses 2-byte values, the first byte specifying the number of consecutive pixels that use a color index and the second byte specifying the index. For more information about bitmap compression, see the description of the BITMAPINFOHEADER, BITMAPFILEHEADER, BITMAPV4HEADER, and BITMAPV5HEADER structures.

An application can create a DIB from a DDB by initializing the required structures and calling the GetDIBits function. To determine whether a device supports this function, call the GetDeviceCaps function, specifying RC_DI_BITMAP as the RASTERCAPS flag.

An application that needs to copy a bitmap can use TransparentBlt to copy all pixels in a source bitmap to a destination bitmap except those pixels that match the transparent color.

An application can use a DIB to set pixels on the display device by calling the SetDIBitsToDevice or the StretchDIBits function. To determine whether a device supports the SetDIBitsToDevice function, call the GetDeviceCaps function, specifying RC_DIBTODEV as the RASTERCAPS flag. Specify RC_STRETCHDIB as the RASTERCAPS flag to determine if the device supports StretchDIBits.

An application that simply needs to display a pre-existing DIB can use the SetDIBitsToDevice function. For example, a spreadsheet application can open existing charts and display them in a window by using the SetDIBitsToDevice function. To repeatedly redraw a bitmap in a window, however, the application should use the BitBlt function. For example, a multimedia application that combines animated graphics with sound would benefit from calling the BitBlt function because it executes faster than SetDIBitsToDevice.


Device-Dependent Bitmaps

Note Device-dependent bitmaps are supported only for compatibility with applications written for early versions of 16-bit Windows (prior to 3.0). If you are writing a Win32-based application, or porting a 16-bit Windows-based application to the Win32 API, you should use DIBs.

DDBs are described by using a single structure, the BITMAP structure. The members of this structure specify the width and height of a rectangular region, in pixels; the width of the array that maps entries from the device palette to pixels; and the device's color format, in terms of color planes and bits per pixel. An application can retrieve the color format of a device by calling the GetDeviceCaps function and specifying the appropriate constants.

There are two types of DDBs: discardable and nondiscardable. A discardable DDB is a bitmap that the system discards if the bitmap is not selected into a DC and if system memory is low. The CreateDiscardableBitmap function creates discardable bitmaps. The CreateBitmap, CreateCompatibleBitmap, and CreateBitmapIndirect functions create nondiscardable bitmaps.

An application can create a DDB from a DIB by initializing the required structures and calling the CreateDIBitmap function. Specifying CBM_INIT in the call to CreateDIBitmap is equivalent to calling the CreateCompatibleBitmap function to create a DDB in the format of the device and then calling the SetDIBits function to translate the DIB bits to the DDB. To determine whether a device supports the SetDIBits function, call the GetDeviceCaps function, specifying RC_DI_BITMAP as the RASTERCAPS flag.


Bitmap Header Types

The bitmap has four basic header types:

  • BITMAPCOREHEADER
  • BITMAPINFOHEADER
  • BITMAPV4HEADER
  • BITMAPV5HEADER

The four types of bitmap headers are differentiated by the Size member, which is the first DWORD in each of the structures.

The BITMAPV5HEADER structure is an extended BITMAPV4HEADER structure, which is an extended BITMAPINFOHEADER structure. However, the BITMAPINFOHEADER and BITMAPCOREHEADER have only the Size member in common with other bitmap header structures.

The BITMAPCOREHEADER and BITMAPV4HEADER formats have been superseded by BITMAPINFOHEADER and BITMAPV5HEADER formats, respectively. The BITMAPCOREHEADER and BITMAPV4HEADER formats are presented for completeness and backward compatibility.

The format for a DIB is the following (for more information, see Bitmap Storage):

  • a BITMAPFILEHEADER structure
  • either a BITMAPCOREHEADER, a BITMAPINFOHEADER, a BITMAPV4HEADER, or a BITMAPV5HEADER structure.
  • an optional color table, which is either a set of RGBQUAD structures or a set of RGBTRIPLE structures.
  • the bitmap data
  • optional Profile data

A color table describes how pixel values correspond to RGB color values. RGB is a model for describing colors that are produced by emitting light.

Profile data refers to either the profile file name (linked profile) or the actual profile bits (embedded profile). The file format places the profile data at the end of the file. The Win32 API format usually places the profile data just after the color table (if present). However, if the function receives a packed DIB, the profile data comes after the bitmap bits, like in the file format.

Profile data will only exist for BITMAPV5HEADER structures where bV5CSType is PROFILE_LINKED or PROFILE_EMBEDDED. For Win32 functions that receive packed DIBs, the profile data comes after the bitmap data.

A palettized device is any device that uses palettes to assign colors. The classic example of a palettized device is a display running in 8 bit color depth (that is, 256 colors). The display in this mode uses a small color table to assign colors to a bitmap. The colors in a bitmap are assigned to the closest color in the palette that the device is using. The palettized device does not create an optimal palette for displaying the bitmap; it simply uses whatever is in the current palette. Applications are responsible for creating a palette and selecting it into the system. In general, 16-, 24-, and 32-bits-per-pixel (bpp) bitmaps do not contain color tables (a.k.a. optimal palettes for the bitmap); the application is responsible for generating a optimal palette in this case. However, 16-, 24-, and 32-bpp bitmaps can contain such optimal color tables for displaying on palettized devices; in this case the application just needs to create a palette based off the color table present in the bitmap file.

Bitmaps that are 1, 4, or 8 bpp must have a color table with a maximum size based on the bpp. The maximum size for 1, 4, and 8 bpp bitmaps is 2 to the power of the bpp. Thus, a 1 bpp bitmap has a maximum of two colors, the 4 bpp bitmap has a maximum of 16 colors, and the 8 bpp bitmap has a maximum of 256 colors.

Bitmaps that are 16-, 24-, or 32-bpp do not require color tables, but may have them to specify colors for palettized devices. If a color table is present for 16-, 24-, or 32-bpp bitmap the ClrUsed field will specify the size of the color table and the color table must have that many colors in it. ClrUsed of zero indicates no color table.

The red, green, and blue bit field masks for BI_BITFIELD bitmaps immediately follow the BITMAPINFOHEADER, BITMAPV4HEADER, and BITMAPV5HEADER structures. The BITMAPV4HEADER and BITMAPV5HEADER structures contain additional members for red, green, and blue masks as follows.

Member | Meaning
RedMask | Color mask that specifies the red component of each pixel, valid only if the Compression member is set to BI_BITFIELDS.
GreenMask | Color mask that specifies the green component of each pixel, valid only if the Compression member is set to BI_BITFIELDS.
BlueMask | Color mask that specifies the blue component of each pixel, valid only if the Compression member is set to BI_BITFIELDS.

When the biCompression member of BITMAPINFOHEADER is set to BI_BITFIELDS and the function receives an argument of type LPBITMAPINFO, the color masks will immediately follow the header. The color table, if present, will follow the color masks. BITMAPCOREHEADER bitmaps do not support color masks.

By default, bitmap data is bottom-up in its format. Bottom-up means that the first scan line in the bitmap data is the last scan line to be displayed. For example, the 0th pixel of the 0th scan line of the bitmap data of a 10-pixel by 10-pixel bitmap will be the 0th pixel of the 9th scan line of the displayed or printed image. Run-length encoded (RLE) format bitmaps and BITMAPCOREHEADER bitmaps can not be top-down bitmaps. The scan lines are DWORD aligned, except for RLE-compressed bitmaps. They must be padded for scan line widths, in bytes, that are not evenly divisible by four, except for RLE compressed bitmaps. For example, a 10- by 10-pixel 24-bpp bitmap will have two padding bytes at the end of each scan line.


JPEG and PNG Extensions for Specific Bitmap Functions and Structures

Starting with the Microsoft® Windows® 98 and Windows 2000 operating systems, the StretchDIBits and SetDIBitsToDevice functions have been extended to allow JPEG and PNG images to be passed as the source image to printer devices. This extension is not intended as a means to supply general JPEG and PNG decompression to applications, but rather to allow applications to send JPEG- and PNG-compressed images directly to printers having hardware support for JPEG and PNG images.

The BITMAPINFOHEADER, BITMAPV4HEADER and BITMAPV5HEADER structures are extended to allow specification of biCompression values indicating that the bitmap data is a JPEG or PNG image. These compression values are only valid for SetDIBitsToDevice and StretchDIBits when the hdc parameter specifies a printer device. To support metafile spooling of the printer, the application should not rely on the return value to determine whether the device supports the JPEG or PNG file. The application must issue QUERYESCSUPPORT with the corresponding escape before calling SetDIBitsToDevice and StretchDIBits. If the validation escape fails, the application must then fall back on its own JPEG or PNG support to decompress the image into a bitmap.


Bitmaps, Device Contexts, and Drawing Surfaces

A device context (DC) is a data structure defining the graphics objects, their associated attributes, and the graphics modes affecting output on a device. To creates a DC, call the CreateDC function; to retrieve a DC, call the GetDC function.

Before returning a handle that identifies that DC, the system selects a drawing surface into the DC. If the application called the CreateDC function to create a device context for a VGA display, the dimensions of this drawing surface are 640-by-480 pixels. If the application called the GetDC function, the dimensions reflect the size of the client area.

Before an application can begin drawing, it must select a bitmap with the appropriate width and height into the DC by calling the SelectObject function. When an application passes the handle to the DC to one of the graphics device interface (GDI) drawing functions, the requested output appears on the drawing surface selected into the DC.

For more information, see Memory Device Contexts.


Bitmap Creation

The Win32 API provides a number of functions to create bitmaps. To create a bitmap, use the CreateBitmap, CreateBitmapIndirect, or CreateCompatibleBitmap function, CreateDIBitmap, and CreateDiscardableBitmap.

These functions all you to specify the width and height, in pixels, of the bitmap. The CreateBitmap and CreateBitmapIndirect function also allow you to specify the number of color planes and the number of bits required to identify the color. On the other hand, the CreateCompatibleBitmap and CreateDiscardableBitmap functions use a specified device context to obtain the number of color planes and the number of bits required to identify the color.

The CreateDIBitmap function creates a device-dependent bitmap from a device-independent bitmap. It contains a color table that describes how pixel values correspond to RGB color values. For more information, see Device-Dependent Bitmaps and Device-Independent Bitmaps.

After the bitmap has been created, you cannot change its size, number of color planes, or number of bits required to identify the color.

When you no longer need a bitmap, call the DeleteObject function to delete it.


Bitmap Rotation

The Win32 API provides a function to copy a bitmap into a parallelogram; this function, PlgBlt, performs a bit-block transfer from a rectangle in a source device context into a parallelogram in a destination device context. In order to rotate the bitmap, an application must provide the coordinates, in world units, to be used for the corners of the parallelogram. (For more information about rotation and world units, see Coordinate Spaces and Transformations.)


Bitmap Scaling

The Win32 API also provides a function to scale a bitmap; this function, StretchBlt, performs a bit-block transfer from a rectangle in a source device context into a rectangle in a destination device context. However, unlike the BitBlt function, which duplicates the source rectangle dimensions in the destination rectangle, StretchBlt allows an application to specify the dimensions of both the source and the destination rectangles. When the destination bitmap is smaller than the source bitmap, the system combines rows or columns of color data (or both) in the bitmap before rendering the corresponding image on the display device. The system combines the color data according to the specified stretch mode, which the application defines by calling the SetStretchBltMode function. When the destination bitmap is larger than the source bitmap, the system scales or magnifies each pixel in the resultant image accordingly.


Bitmaps as Brushes

The Win32 API provides a number of functions that use the brush currently selected into a device context to perform bitmap operations. For example, the PatBlt function replicates the brush in a rectangular region within a window, and the FloodFill function replicates the brush inside an area in a window bounded by the specified color (unlike PatBlt, FloodFill does fill nonrectangular shapes).

The FloodFill function replicates the brush within a region bounded by a specified color. However, unlike the PatBlt function, FloodFill does not combine the color data for the brush with the color data for the pixels on the display; it simply sets the color of all pixels within the enclosed region on the display to the color of the brush that is currently selected into the device context.


Bitmap Storage

Bitmaps should be saved in a file that uses the established bitmap file format and assigned a name with the three-character .bmp extension. The established bitmap file format consists of a BITMAPFILEHEADER structure followed by a BITMAPINFOHEADER, BITMAPV4HEADER, or BITMAPV5HEADER structure. An array of RGBQUAD structures (also called a color table) follows the bitmap information header structure. The color table is followed by a second array of indexes into the color table (the actual bitmap data).

The bitmap file format is shown in the following illustration.

Windows 95 and Windows NT 4.0: Replace the BITMAPINFOHEADER structure with the BITMAPV4HEADER structure.

Windows 98 and Windows 2000 or later: Replace the BITMAPINFOHEADER structure with the BITMAPV5HEADER structure.

The members of the BITMAPFILEHEADER structure identify the file; specify the size of the file, in bytes; and specify the offset from the first byte in the header to the first byte of bitmap data. The members of the BITMAPINFOHEADER, BITMAPV4HEADER, or BITMAPV5HEADER structure specify the width and height of the bitmap, in pixels; the color format (count of color planes and color bits-per-pixel) of the display device on which the bitmap was created; whether the bitmap data was compressed before storage and the type of compression used; the number of bytes of bitmap data; the resolution of the display device on which the bitmap was created; and the number of colors represented in the data. The RGBQUAD structures specify the RGB intensity values for each of the colors in the device's palette. The color-index array maps indexes values from the RGBQUAD array to pixels in a rectangular region on the display.

The following hexadecimal output shows the contents of the file Redbrick.bmp.

0000    42 4d 76 02 00 00 00 00  00 00 76 00 00 00 28 00
0010    00 00 20 00 00 00 20 00  00 00 01 00 04 00 00 00
0020    00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
0030    00 00 00 00 00 00 00 00  00 00 00 00 80 00 00 80
0040    00 00 00 80 80 00 80 00  00 00 80 00 80 00 80 80
0050    00 00 80 80 80 00 c0 c0  c0 00 00 00 ff 00 00 ff
0060    00 00 00 ff ff 00 ff 00  00 00 ff 00 ff 00 ff ff
0070    00 00 ff ff ff 00 00 00  00 00 00 00 00 00 00 00
0080    00 00 00 00 00 00 00 00  00 00 00 00 00 00 09 00
0090    00 00 00 00 00 00 11 11  01 19 11 01 10 10 09 09
00a0    01 09 11 11 01 90 11 01  19 09 09 91 11 10 09 11
00b0    09 11 19 10 90 11 19 01  19 19 10 10 11 10 09 01
00c0    91 10 91 09 10 10 90 99  11 11 11 11 19 00 09 01
00d0    91 01 01 19 00 99 11 10  11 91 99 11 09 90 09 91
00e0    01 11 11 11 91 10 09 19  01 00 11 90 91 10 09 01
00f0    11 99 10 01 11 11 91 11  11 19 10 11 99 10 09 10
0100    01 11 11 11 19 10 11 09  09 10 19 10 10 10 09 01
0110    11 19 00 01 10 19 10 11  11 01 99 01 11 90 09 19
0120    11 91 11 91 01 11 19 10  99 00 01 19 09 10 09 19
0130    10 91 11 01 11 11 91 01  91 19 11 00 99 90 09 01
0140    01 99 19 01 91 10 19 91  91 09 11 99 11 10 09 91
0150    11 10 11 91 99 10 90 11  01 11 11 19 11 90 09 11
0160    00 19 10 11 01 11 99 99  99 99 99 99 99 99 09 99
0170    99 99 99 99 99 99 00 00  00 00 00 00 00 00 00 00
0180    00 00 00 00 00 00 90 00  00 00 00 00 00 00 00 00
0190    00 00 00 00 00 00 99 11  11 11 19 10 19 19 11 09
01a0    10 90 91 90 91 00 91 19  19 09 01 10 09 01 11 11
01b0    91 11 11 11 10 00 91 11  01 19 10 11 10 01 01 11
01c0    90 11 11 11 91 00 99 09  19 10 11 90 09 90 91 01
01d0    19 09 91 11 01 00 90 10  19 11 00 11 11 00 10 11
01e0    01 10 11 19 11 00 90 19  10 91 01 90 19 99 00 11
01f0    91 01 11 01 91 00 99 09  09 01 10 11 91 01 10 91
0200    99 11 10 90 91 00 91 11  00 10 11 01 10 19 19 09
0210    10 00 99 01 01 00 91 01  19 91 19 91 11 09 10 11
0220    00 91 00 10 90 00 99 01  11 10 09 10 10 19 09 01
0230    91 90 11 09 11 00 90 99  11 11 11 90 19 01 19 01
0240    91 01 01 19 09 00 91 10  11 91 99 09 09 90 11 91
0250    01 19 11 11 91 00 91 19  01 00 11 00 91 10 11 01
0260    11 11 10 01 11 00 99 99  99 99 99 99 99 99 99 99
0270    99 99 99 99 99 90

The following table shows the data bytes associated with the structures in a bitmap file.

Structure | Corresponding bytes
BITMAPFILEHEADER | 0x00 – 0x0D
BITMAPINFOHEADER | 0x0E – 0x31
RGBQUAD array | 0x32 – 0x75
Color-index array | 0x76 – 0x275


Bitmap Compression

The Win32 API supports formats for compressing bitmaps that define their colors with 8 or 4 bits-per-pixel. Compression reduces the disk and memory storage required for the bitmap.

Compression forms part of the following member names in the bitmap information header structures for different platforms. In the discussion that follows, compression is used to mean all of these variants.

Operating system | Compression
Windows NT 3.51 and earlier | biCompression
Windows NT 4.0 and Windows 95 | bV4Compression
Windows 2000 and Windows 98 | bV5Compression

When the Compression member of the bitmap information header structure is BI_RLE8, a run-length encoding (RLE) format is used to compress an 8-bit bitmap. This format can be compressed in encoded or absolute modes. Both modes can occur anywhere in the same bitmap:

  • Encoded mode consists of two bytes: the first byte specifies the number of consecutive pixels to be drawn using the color index contained in the second byte. In addition, the first byte of the pair can be set to zero to indicate an escape character that denotes the end of a line, the end of a bitmap, or a delta, depending on the value of the second byte. The interpretation of the escape depends on the value of the second byte of the pair, which can be one of the following values.
Value | Meaning
0 | End of line.
1 | End of bitmap.
2 | Delta. The 2 bytes following the escape contain unsigned values indicating the horizontal and vertical offsets of the next pixel from the current position.

  • In absolute mode, the first byte is zero and the second byte is a value in the range 03H through FFH. The second byte represents the number of bytes that follow, each of which contains the color index of a single pixel. When the second byte is two or less, the escape has the same meaning as encoded mode. In absolute mode, each run must be aligned on a word boundary.

The following example shows the hexadecimal values of an 8-bit compressed bitmap:

03 04 05 06 00 03 45 56 67 00 02 78 00 02 05 01
02 78 00 00 09 1E 00 01

The bitmap expands as follows (two-digit values represent a color index for a single pixel):

04 04 04
06 06 06 06 06
45 56 67
78 78
move current position 5 right and 1 down
78 78
end of line
1E 1E 1E 1E 1E 1E 1E 1E 1E
end of RLE bitmap

When the Compression member is BI_RLE4, the bitmap is compressed by using a run-length encoding format for a 4-bit bitmap, which also uses encoded and absolute modes:

  • In encoded mode, the first byte of the pair contains the number of pixels to be drawn using the color indexes in the second byte. The second byte contains two color indexes, one in its high-order 4 bits and one in its low-order 4 bits. The first of the pixels is drawn using the color specified by the high-order 4 bits, the second is drawn using the color in the low-order 4 bits, the third is drawn using the color in the high-order 4 bits, and so on, until all the pixels specified by the first byte have been drawn.
  • In absolute mode, the first byte is zero. The second byte contains the number of color indexes that follow. Subsequent bytes contain color indexes in their high- and low-order 4 bits, one color index for each pixel. In absolute mode, each run must be aligned on a word boundary. The end-of-line, end-of-bitmap, and delta escapes described for BI_RLE8 also apply to BI_RLE4 compression.

The following example shows the hexadecimal values of a 4-bit compressed bitmap:

03 04 05 06 00 06 45 56 67 00 04 78 00 02 05 01
04 78 00 00 09 1E 00 01

The bitmap expands as follows (single-digit values represent a color index for a single pixel):

0 4 0
0 6 0 6 0
4 5 5 6 6 7
7 8 7 8
move current position 5 right and 1 down
7 8 7 8
end of line
1 E 1 E 1 E 1 E 1
end of RLE bitmap


Alpha Blending

Alpha blending is used to display an alpha bitmap, which is a bitmap that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire bitmap is transparent) to 255 (the entire bitmap is opaque).

Alpha blending mechanisms are invoked by calling AlphaBlend, which references the BLENDFUNCTION structure.


Alpha Values Per Pixel

Alpha values per pixel are only supported for 32-bpp BI_RGB. This formula is defined as :

typedef struct {
  BYTE   Blue;
  BYTE   Green;
  BYTE    Red;
  BYTE    Alpha;
};

This is represented in memory as shown in the following table.

31:24

23:16

15:08

07:00

Alpha

Red

Green

Blue


Global Alpha Blending Settings

Bitmaps may also be displayed with a transparency factor applied to the entire bitmap. Any bitmap format can be displayed with a global constant alpha value by setting SourceConstantAlpha in the BLENDFUNCTION structure. The global constant alpha value has 256 levels of transparency, from 0 (entire bitmap is completely transparent) to 255 (entire bitmap is completely opaque). The global constant alpha value is combined with the per-pixel alpha value.


Smooth Shading

Smooth shading is a method of shading a region with a color gradient. Including color information, along with the bounds of drawing primitive, specifies the color gradient. GDI linearly interpolates the color of the inside of the primitive passed on the color endpoints. Color and vertex information is included with position information in the TRIVERTEX structure.

Use the GradientFill function to fill a triangle or rectangle structure. To fill a triangle with smooth shading, call GradientFill with the three triangle endpoints. To fill a rectangle with smooth shading, call GradientFill with the upper-left and lower-right rectangle coordinates. GradientFill references the TRIVERTEX, GRADIENT_RECT, and GRADIENT_TRIANGLE structures.

For an example, see Drawing a Shaded Triangle.


ICM-Enabled Bitmap Functions

Windows 98 and Windows 2000 have been designed to work with Microsoft Image Color Management (ICM). ICM technology ensures that a color image, graphic object, or text object is rendered as closely as possible to its original intent on any device, despite differences in imaging technologies and color capabilities between devices. Whether you are scanning an image or other graphic on a color scanner, downloading it over the Internet, viewing or editing it onscreen, or printing it on paper, film, or other media, ICM 2.0 helps you keep colors consistent and accurate. For more information on ICM, see About Image Color Management Version_2.0.

There are various functions in the graphics device interface (GDI) that use or operate on color data. The following bitmap functions are enabled for use with ICM:

  • BitBlt
  • CreateDIBitmap
  • CreateDIBSection
  • MaskBlt
  • SetDIBColorTable
  • StretchBlt
  • SetDIBits
  • SetDIBitsToDevice
  • StretchDIBits


Using Bitmaps

  • Capturing an Image
  • Scaling an Image
  • Storing an Image
  • Drawing a Shaded Rectangle
  • Drawing a Shaded Triangle
  • Testing a Printer for JPEG or PNG Support
  • Sizing a JPEG or PNG Image


Capturing an Image

You can use a bitmap to capture an image, and you can store the captured image in memory, display it at a different location in your application's window, or display it in another window.

In some cases, you may want your application to capture images and store them only temporarily. For example, when you scale or zoom a picture created in a drawing application, the application must temporarily save the normal view of the image and display the zoomed view. Later, when the user selects the normal view, the application must replace the zoomed image with a copy of the normal view that it temporarily saved.

To store an image temporarily, your application must call CreateCompatibleDC to create a DC that is compatible with the current window DC. After you create a compatible DC, you create a bitmap with the appropriate dimensions by calling the CreateCompatibleBitmap function and then select it into this device context by calling the SelectObject function.

After the compatible device context is created and the appropriate bitmap has been selected into it, you can capture the image. The BitBlt function captures images. This function performs a bit block transfer — that is, it copies data from a source bitmap into a destination bitmap. However, the two arguments to this function are not bitmap handles. Instead, BitBlt receives handles that identify two device contexts and copies the bitmap data from a bitmap selected into the source DC into a bitmap selected into the target DC. In this case, the target DC is the compatible DC, so when BitBlt completes the transfer, the image has been stored in memory. To redisplay the image, call BitBlt a second time, specifying the compatible DC as the source DC and a window (or printer) DC as the target DC.

The following example code, from an application that captures an image of the entire desktop, creates a compatible device context and a bitmap with the appropriate dimensions, selects the bitmap into the compatible DC, and then copies the image using the BitBlt function.

// Create a normal DC and a memory DC for the entire screen. The
// normal DC provides a "snapshot" of the screen contents. The
// memory DC keeps a copy of this "snapshot" in the associated
// bitmap.

hdcScreen = CreateDC("DISPLAY", NULL, NULL, NULL);
hdcCompatible = CreateCompatibleDC(hdcScreen);

// Create a compatible bitmap for hdcScreen.

hbmScreen = CreateCompatibleBitmap(hdcScreen,
                     GetDeviceCaps(hdcScreen, HORZRES),
                     GetDeviceCaps(hdcScreen, VERTRES));

if (hbmScreen == 0)
    errhandler("hbmScreen", hwnd);

// Select the bitmaps into the compatible DC.

if (!SelectObject(hdcCompatible, hbmScreen))
    errhandler("Compatible Bitmap Selection", hwnd);

        // Hide the application window.

        ShowWindow(hwnd, SW_HIDE);

         //Copy color data for the entire display into a
         //bitmap that is selected into a compatible DC.

        if (!BitBlt(hdcCompatible,
               0,0,
               bmp.bmWidth, bmp.bmHeight,
               hdcScreen,
               0,0,
               SRCCOPY))

        errhandler("Screen to Compat Blt Failed", hwnd);

        // Redraw the application window.

        ShowWindow(hwnd, SW_SHOW);


Scaling an Image

Some applications scale images — that is, they display zoomed or reduced views of an image. For example, a drawing application may provide a zoom feature that enables the user to view and edit a drawing on a pixel-by-pixel basis.

Applications scale images by calling the StretchBlt function. Like the BitBlt function, StretchBlt copies bitmap data from a bitmap in a source DC into a bitmap in a target DC. However, unlike the BitBlt function, StretchBlt scales the image based on the specified dimensions of the source and target rectangles. If the source rectangle is larger than the target rectangle, the resultant image will appear to have shrunk; if the source rectangle is smaller than the target rectangle, the resultant image will appear to have expanded.

If the target rectangle is smaller than the source rectangle, StretchBlt removes color data from the image according to a specified stretch mode as shown in the following table.

Stretch mode | Method
BLACKONWHITE | Performs a logical AND operation on the color data for the eliminated pixels and the color data for the remaining pixels.
WHITEONBLACK | Performs a logical OR operation on the color data for the eliminated pixels and the color data for the remaining pixels.
COLORONCOLOR | Eliminates the color data of the deleted pixels completely.
HALFTONE | Approximates the original (source) color data in the destination.

You set the stretch mode by calling the SetStretchBltMode function.

The following example code is taken from an application that displays an image either at its original size or at twice its original size. (This application uses the default stretch mode.)

    hdcScaled = CreateCompatibleDC(hdcScreen);

    hbmScaled = CreateCompatibleBitmap(hdcScreen,
                    GetDeviceCaps(hdcScreen, HORZRES) * 2,
                    GetDeviceCaps(hdcScreen, VERTRES) * 2);

    if (hbmScaled == 0)
        errhandler("hbmScaled", hwnd);

    // Select the bitmaps into the compatible DC.

    if (!SelectObject(hdcScaled, hbmScaled))
        errhandler("Scaled Bitmap Selection", hwnd);

case WM_COMMAND:     // message: command from application menu
    switch(wParam)
    {
        case IDM_SCALEX1:
            if (fBlt)
            {
                 fScaled = FALSE;
                 hdcWin = GetDC(hwnd);
                 BitBlt(hdcWin,
                    0,0,
                    bmp.bmWidth, bmp.bmHeight,
                    hdcCompatible,
                    0,0,
                    SRCCOPY);
                 ReleaseDC(hwnd, hdcWin);
            }
            break;

        case IDM_SCALEX2:
            if (fBlt)
            {
                 fScaled = TRUE;
                 StretchBlt(hdcScaled,
                     0, 0,
                     bmp.bmWidth * 2, bmp.bmHeight * 2,
                     hdcCompatible,
                     0, 0,
                     bmp.bmWidth, bmp.bmHeight,
                     SRCCOPY);

                 hdcWin = GetDC(hwnd);
                 BitBlt(hdcWin,
                    0,0,
                    bmp.bmWidth, bmp.bmHeight,
                    hdcScaled,
                    0,0,
                    SRCCOPY);
                 ReleaseDC(hwnd, hdcWin);
            }
            break;


Storing an Image

Many applications store images permanently as files. For example, drawing applications store pictures, spreadsheet applications store charts, CAD applications store drawings, and so on.

If you are writing an application that stores a bitmap image in a file, you should use the bitmap file format described in Bitmap Storage. To store a bitmap in this format, you must use a BITMAPINFOHEADER, a BITMAPV4HEADER, or a BITMAPV5HEADER structure and an array of RGBQUAD structures, as well as an array of palette indexes.

The following example code defines a function that uses a BITMAPINFO structure and allocates memory for and initializes members within a BITMAPINFOHEADER structure. Note that the BITMAPINFO structure cannot be used with either a BITMAPV4HEADER or a BITMAPV5HEADER structure.

PBITMAPINFO CreateBitmapInfoStruct(HWND hwnd, HBITMAP hBmp)
{
    BITMAP bmp;
    PBITMAPINFO pbmi;
    WORD    cClrBits;

    // Retrieve the bitmap's color format, width, and height.
    if (!GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp))
        errhandler("GetObject", hwnd);

    // Convert the color format to a count of bits.
    cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);
    if (cClrBits == 1)
        cClrBits = 1;
    else if (cClrBits <= 4)
        cClrBits = 4;
    else if (cClrBits <= 8)
        cClrBits = 8;
    else if (cClrBits <= 16)
        cClrBits = 16;
    else if (cClrBits <= 24)
        cClrBits = 24;
    else cClrBits = 32;

    // Allocate memory for the BITMAPINFO structure. (This structure
    // contains a BITMAPINFOHEADER structure and an array of RGBQUAD
    // data structures.)

     if (cClrBits != 24)
         pbmi = (PBITMAPINFO) LocalAlloc(LPTR,
                    sizeof(BITMAPINFOHEADER) +
                    sizeof(RGBQUAD) * (1<< cClrBits));

     // There is no RGBQUAD array for the 24-bit-per-pixel format.

     else
         pbmi = (PBITMAPINFO) LocalAlloc(LPTR,
                    sizeof(BITMAPINFOHEADER));

    // Initialize the fields in the BITMAPINFO structure.

    pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    pbmi->bmiHeader.biWidth = bmp.bmWidth;
    pbmi->bmiHeader.biHeight = bmp.bmHeight;
    pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
    pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
    if (cClrBits < 24)
        pbmi->bmiHeader.biClrUsed = (1<<cClrBits);

    // If the bitmap is not compressed, set the BI_RGB flag.
    pbmi->bmiHeader.biCompression = BI_RGB;

    // Compute the number of bytes in the array of color
    // indices and store the result in biSizeImage.
    // For Windows NT/2000, the width must be DWORD aligned unless
    // the bitmap is RLE compressed. This example shows this.
    // For Windows 95/98, the width must be WORD aligned unless the
    // bitmap is RLE compressed.
    pbmi->bmiHeader.biSizeImage = ((pbmi->bmiHeader.biWidth * cClrBits +31) & ~31) /8
                                  * pbmi->bmiHeader.biHeight;
    // Set biClrImportant to 0, indicating that all of the
    // device colors are important.
     pbmi->bmiHeader.biClrImportant = 0;
     return pbmi;
 }

The following example code defines a function that initializes the remaining structures, retrieves the array of palette indices, opens the file, copies the data, and closes the file.

void CreateBMPFile(HWND hwnd, LPTSTR pszFile, PBITMAPINFO pbi,
                  HBITMAP hBMP, HDC hDC)
 {
     HANDLE hf;                 // file handle
    BITMAPFILEHEADER hdr;       // bitmap file-header
    PBITMAPINFOHEADER pbih;     // bitmap info-header
    LPBYTE lpBits;              // memory pointer
    DWORD dwTotal;              // total count of bytes
    DWORD cb;                   // incremental count of bytes
    BYTE *hp;                   // byte pointer
    DWORD dwTmp;

    pbih = (PBITMAPINFOHEADER) pbi;
    lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);

    if (!lpBits)
         errhandler("GlobalAlloc", hwnd);

    // Retrieve the color table (RGBQUAD array) and the bits
    // (array of palette indices) from the DIB.
    if (!GetDIBits(hDC, hBMP, 0, (WORD) pbih->biHeight, lpBits, pbi,
        DIB_RGB_COLORS))
    {
        errhandler("GetDIBits", hwnd);
    }

    // Create the .BMP file.
    hf = CreateFile(pszFile,
                   GENERIC_READ | GENERIC_WRITE,
                   (DWORD) 0,
                    NULL,
                   CREATE_ALWAYS,
                   FILE_ATTRIBUTE_NORMAL,
                   (HANDLE) NULL);
    if (hf == INVALID_HANDLE_VALUE)
        errhandler("CreateFile", hwnd);
    hdr.bfType = 0x4d42;        // 0x42 = "B" 0x4d = "M"
    // Compute the size of the entire file.
    hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) +
                 pbih->biSize + pbih->biClrUsed
                 * sizeof(RGBQUAD) + pbih->biSizeImage);
    hdr.bfReserved1 = 0;
    hdr.bfReserved2 = 0;

    // Compute the offset to the array of color indices.
    hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) +
                    pbih->biSize + pbih->biClrUsed
                    * sizeof (RGBQUAD);

    // Copy the BITMAPFILEHEADER into the .BMP file.
    if (!WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER),
        (LPDWORD) &dwTmp,  NULL))
    {
       errhandler("WriteFile", hwnd);
    }

    // Copy the BITMAPINFOHEADER and RGBQUAD array into the file.
    if (!WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER)
                  + pbih->biClrUsed * sizeof (RGBQUAD),
                  (LPDWORD) &dwTmp, ( NULL))
        errhandler("WriteFile", hwnd);

    // Copy the array of color indices into the .BMP file.
    dwTotal = cb = pbih->biSizeImage;
    hp = lpBits;
    if (!WriteFile(hf, (LPSTR) hp, (int) cb, (LPDWORD) &dwTmp,NULL))
           errhandler("WriteFile", hwnd);

    // Close the .BMP file.
     if (!CloseHandle(hf))
           errhandler("CloseHandle", hwnd);

    // Free memory.
    GlobalFree((HGLOBAL)lpBits);
}


Drawing a Shaded Rectangle

To draw a shaded rectangle from [0,0] to [100,32], define a TRIVERTEX array with two elements and a single GRADIENT_RECT structure. The following example shows a horizontal GradientFill rectangle call.

TRIVERTEX        vert[2] ;
GRADIENT_RECT    gRect;
vert [0] .x      = 0;
vert [0] .y      = 0;
vert [0] .Red    = 0x0000;
vert [0] .Green  = 0x0000;
vert [0] .Blue   = 0x0000;
vert [0] .Alpha  = 0x0000;

vert [1] .x      = 100;
vert [1] .y      = 32;
vert [1] .Red    = 0x0000;
vert [1] .Green  = 0x0000;
vert [1] .Blue   = 0xff00;
vert [1] .Alpha  = 0x0000;

gRect.UpperLeft  = 0;
gRect.LowerRight = 1;
GradientFill(hdc,vert,2,&gRect,1,GRADIENT_FILL_RECT_H);


Drawing a Shaded Triangle

To draw a shaded triangle from [0,0] to [100,32], define a TRIVERTEX structure with three elements and a single GRADIENT_TRIANGLE structure. The following example shows a GRADIENT_FILL_TRIANGLE call.

TRIVERTEX        vert [4] ;
GRADIENT_TRIANGLE    gTri;
vert [0] .x       =  0;
vert [0] .y       =  0;
vert [0] .Red     =  0x0000;
vert [0] .Green   =  0x0000;
vert [0] .Blue    =  0x0000;
vert [0] .Alpha   =  0x0000;

vert [1] .x       =  100;
vert [1] .y       =  0;
vert [1] .Red     =  0x0000;
vert [1] .Green   =  0x0000;
vert [1] .Blue    =  0xff00;
vert [1] .Alpha   =  0x0000;

vert [2] .x       =  100;
vert [2] .y       =  32;
vert [2] .Red     =  0x0000;
vert [2] .Green   =  0x0000;
vert [2] .Blue    =  0xff00;
vert [2] .Alpha   =  0x0000;

vert [3] .x       =  0;
vert [3] .y       =  32;
vert [3] .Red     =  0xff00;
vert [3] .Green   =  0xff00;
vert [3] .Blue    =  0xff00;
vert [3] .Alpha   =  0x0000;

gTRi[0].Vertex1   = 0
gTRi[0].Vertex2   = 1
gTRi[0].Vertex3   = 2

gTRi[1].Vertex1   = 0
gTRi[1].Vertex2   = 2
gTRi[1].Vertex3   = 3
GradientFill(hdc,vert,4,&gTRI,1,GRADIENT_FILL_TRIANGLE);


Testing a Printer for JPEG or PNG Support

The SetDIBitsToDevice function uses color data from a DIB to set the pixels in the specified rectangle on the device that is associated with the destination device context.

Windows 98 and Windows 2000 or later: SetDIBitsToDevice is extended to allow a JPEG or PNG image to be passed as the source image.

For example:

//
// pvJpgImage points to a buffer containing the JPEG image
// nJpgImageSize is the size of the buffer
// ulJpgWidth is the width of the JPEG image
// ulJpgHeight is the height of the JPEG image
//

//
// Check if CHECKJPEGFORMAT is supported (device has JPEG support)
// and use it to verify that device can handle the JPEG image.
//

ul = CHECKJPEGFORMAT;

if (
    // Check if CHECKJPEGFORMAT exists:

    (ExtEscape(hdc, QUERYESCSUPPORT,
               sizeof(ul), &ul, 0, 0) > 0) &&

    // Check if CHECKJPEGFORMAT executed without error:

    (ExtEscape(hdc, CHECKJPEGFORMAT,
               pvJpgImage, nJpgImageSize, sizeof(ul), &ul) > 0) &&

    // Check status code returned by CHECKJPEGFORMAT:

    (ul == 1)
   )
{
    //
    // Initialize the BITMAPINFO.
    //

    memset(&bmi, 0, sizeof(bmi));
    bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth       = ulJpgWidth;
    bmi.bmiHeader.biHeight      = -ulJpgHeight; // top-down image
    bmi.bmiHeader.biPlanes      = 1;
    bmi.bmiHeader.biBitCount    = 0;
    bmi.bmiHeader.biCompression = BI_JPEG;
    bmi.bmiHeader.biSizeImage   = nJpgImageSize;

    //
    // Do the SetDIBitsToDevice.
    //

    iRet = SetDIBitsToDevice(hdc,
                             ulDstX, ulDstY,
                             ulDstWidth, ulDstHeight,
                             0, 0,
                             0, ulJpgHeight,
                             pvJpgImage,
                             &bmi,
                             DIB_RGB_COLORS);

    if (iRet == GDI_ERROR)
        return FALSE;
}
else
{
    //
    // Decompress image into a DIB and call SetDIBitsToDevice
    // with the DIB instead.
    //
}


Sizing a JPEG or PNG Image

The StretchDIBits function copies the color data for a rectangle of pixels in a DIB to the specified destination rectangle. If the destination rectangle is larger than the source rectangle, this function stretches the rows and columns of color data to fit the destination rectangle. If the destination rectangle is smaller than the source rectangle, StretchDIBits compresses the rows and columns by using the specified raster operation.

Windows 98 and Windows 2000 or later: StretchDIBits is extended to allow a JPEG or PNG image to be passed as the source image.

For example:

// pvJpgImage points to a buffer containing the JPEG image
// nJpgImageSize is the size of the buffer
// ulJpgWidth is the width of the JPEG image
// ulJpgHeight is the height of the JPEG image
//

//
// Check if CHECKJPEGFORMAT is supported (device has JPEG support)
// and use it to verify that device can handle the JPEG image.
//

ul = CHECKJPEGFORMAT;

if (
    // Check if CHECKJPEGFORMAT exists:

    (ExtEscape(hdc, QUERYESCSUPPORT,
               sizeof(ul), &ul, 0, 0) > 0) &&

    // Check if CHECKJPEGFORMAT executed without error:

    (ExtEscape(hdc, CHECKJPEGFORMAT,
               pvJpgImage, nJpgImageSize, sizeof(ul), &ul) > 0) &&

    // Check status code returned by CHECKJPEGFORMAT:

    (ul == 1)
   )
{
    //
    // Initialize the BITMAPINFO.
    //

    memset(&bmi, 0, sizeof(bmi));
    bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth       = ulJpgWidth;
    bmi.bmiHeader.biHeight      = -ulJpgHeight; // top-down image
    bmi.bmiHeader.biPlanes      = 1;
    bmi.bmiHeader.biBitCount    = 0;
    bmi.bmiHeader.biCompression = BI_JPEG;
    bmi.bmiHeader.biSizeImage   = nJpgImageSize;

    //
    // Do the StretchDIBits.
    //

    iRet = StretchDIBits(hdc,
                         // destination rectangle
                         ulDstX, ulDstY, ulDstWidth, ulDstHeight,
                         // source rectangle
                         0, 0, ulJpgWidth, ulJpgHeight,
                         pvJpgImage,
                         &bmi,
                         DIB_RGB_COLORS,
                         SRCCOPY);

    if (iRet == GDI_ERROR)
        return FALSE;
}
else
{
    //
    // Decompress image into a DIB and call StretchDIBits
    // with the DIB instead.
    //
}


Bitmap Reference

The following elements are used with bitmaps:

  • Bitmap Functions
  • Bitmap Structures
  • Bitmap Macros


Bitmap Functions

The following functions are used with bitmaps.

Function | Description
AlphaBlend | Displays a bitmap with transparent or semitransparent pixels.
BitBlt | Performs a bit-block transfer.
CreateBitmap | Creates a bitmap.
CreateBitmapIndirect | Creates a bitmap.
CreateCompatibleBitmap | Creates a bitmap compatible with a device.
CreateDIBitmap | Creates a device-dependent bitmap (DDB) from a DIB.
CreateDIBSection | Creates a DIB that applications can write to directly.
ExtFloodFill | Fills an area of the display surface with the current brush.
GetBitmapDimensionEx | Gets the dimensions of a bitmap.
GetDIBColorTable | Retrieves RGB color values from a DIB section bitmap.
GetDIBits | Copies a bitmap into a buffer.
GetPixel | Gets the RGB color value of the pixel at a given coordinate.
GetStretchBltMode | Gets the current stretching mode.
GradientFill | Fills rectangle and triangle structures.
LoadBitmap | Loads a bitmap from a module's executable file.
MaskBlt | Combines the color data in the source and destination bitmaps.
PlgBlt | Performs a bit-block transfer.
SetBitmapDimensionEx | Sets the preferred dimensions to a bitmap.
SetDIBColorTable | Sets RGB values in a DIB.
SetDIBits | Sets the pixels in a bitmap using color data from a DIB.
SetDIBitsToDevice | Sets the pixels in a rectangle using color data from a DIB.
SetPixel | Sets the color for a pixel.
SetPixelV | Sets a pixel to the best approximation of a color.
SetStretchBltMode | Sets the bitmap stretching mode.
StretchBlt | Copies a bitmap and stretches or compresses it.
StretchDIBits | Copies the color data in a DIB.
TransparentBlt | Performs a bit-block transfer of color data.

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of Microsoft® Windows®:

  • CreateDiscardableBitmap
  • FloodFill
  • GetBitmapBits
  • SetBitmapBits


AlphaBlend

The AlphaBlend function displays bitmaps that have transparent or semitransparent pixels.

BOOL AlphaBlend(
  HDC hdcDest,                 // handle to destination DC
  int nXOriginDest,            // x-coord of upper-left corner
  int nYOriginDest,            // y-coord of upper-left corner
  int nWidthDest,              // destination width
  int nHeightDest,             // destination height
  HDC hdcSrc,                  // handle to source DC
  int nXOriginSrc,             // x-coord of upper-left corner
  int nYOriginSrc,             // y-coord of upper-left corner
  int nWidthSrc,               // source width
  int nHeightSrc,              // source height
  BLENDFUNCTION blendFunction  // alpha-blending function
);

Parameter

hdcDest
[in] Handle to the destination device context.
nXOriginDest
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nYOriginDest
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nWidthDest
[in] Specifies the width, in logical units, of the destination rectangle.
nHeightDest
[in] Specifies the height, in logical units, of the destination rectangle.
hdcSrc
[in] Handle to the source device context.
nXOriginSrc
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.
nYOriginSrc
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.
nWidthSrc
[in] Specifies the width, in logical units, of the source rectangle.
nHeightSrc
[in] Specifies the height, in logical units, of the source rectangle.
blendFunction
[in] Specifies the alpha-blending function for source and destination bitmaps, a global alpha value to be applied to the entire source bitmap, and format information for the source bitmap. The source and destination blend functions are currently limited to AC_SRC_OVER. See the BLENDFUNCTION and EMRALPHABLEND structures.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can return the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more of the input parameters is invalid.

Remarks

If the source rectangle and destination rectangle are not the same size, the source bitmap is stretched to match the destination rectangle. If the SetStretchBltMode function is used, the iStretchMode value is automatically converted to COLORONCOLOR for this function (that is, BLACKONWHITE, WHITEONBLACK, and HALFTONE are changed to COLORONCOLOR).

The destination coordinates are transformed by using the transformation currently specified for the destination device context. The source coordinates are transformed by using the transformation currently specified for the source device context.

An error occurs (and the function returns FALSE) if the source device context identifies an enhanced metafile device context.

If destination and source bitmaps do not have the same color format, AlphaBlend converts the source bitmap to match the destination bitmap.

AlphaBlend does not support mirroring. If either the width or height of the source or destination is negative, this call will fail.

If the source and destination are the same surface—that is, they are both the screen or the same memory bitmap—and the source and destination rectangles overlap, an error occurs and the function returns FALSE.

The source rectangle must lie completely within the source surface, otherwise an error occurs and the function returns FALSE.

AlphaBlend fails if the width or height of the source or destination is negative.

Note The SourceConstantaAlpha member of BLENDFUNCTION specifies an alpha transparancy value to be used on the entire source bitmap. The SourceConstantAlpha value is combined with any per-pixel alpha values. If SourceConstantAlpha is 0, it is assumed that the image is transparent. Set the SourceConstantAlpha value to 255 (which indicates that the image is opaque) when you only want to use per-pixel alpha values.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Included as a resource in Msimg32.dll.

See Also

Bitmaps Overview, Bitmap Functions


BitBlt

The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.

BOOL BitBlt(
  HDC hdcDest, // handle to destination DC
  int nXDest,  // x-coord of destination upper-left corner
  int nYDest,  // y-coord of destination upper-left corner
  int nWidth,  // width of destination rectangle
  int nHeight, // height of destination rectangle
  HDC hdcSrc,  // handle to source DC
  int nXSrc,   // x-coordinate of source upper-left corner
  int nYSrc,   // y-coordinate of source upper-left corner
  DWORD dwRop  // raster operation code
);

Parameters

hdcDest
[in] Handle to the destination device context.
nXDest
[in] Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.
nYDest
[in] Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.
nWidth
[in] Specifies the logical width of the source and destination rectangles.
nHeight
[in] Specifies the logical height of the source and the destination rectangles.
hdcSrc
[in] Handle to the source device context.
nXSrc
[in] Specifies the logical x-coordinate of the upper-left corner of the source rectangle.
nYSrc
[in] Specifies the logical y-coordinate of the upper-left corner of the source rectangle.
dwRop
[in] Specifies a raster-operation code. These codes define how the color data for the source rectangle is to be combined with the color data for the destination rectangle to achieve the final color.

The following list shows some common raster operation codes.
Value | Description
BLACKNESS | Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the default physical palette.)
CAPTUREBLT | Windows 98/Me, Windows 2000 or later: Includes any windows that are layered on top of your window in the resulting image. By default, the image only contains your window.
DSTINVERT | Inverts the destination rectangle.
MERGECOPY | Merges the colors of the source rectangle with the brush currently selected in hdcDest, by using the Boolean AND operator.
MERGEPAINT | Merges the colors of the inverted source rectangle with the colors of the destination rectangle by using the Boolean OR operator.
NOMIRRORBITMAP | Windows 98/Me, Windows 2000 or later: Prevents the bitmap from being mirrored.
NOTSRCCOPY | Copies the inverted source rectangle to the destination.
NOTSRCERASE | Combines the colors of the source and destination rectangles by using the Boolean OR operator and then inverts the resultant color.
PATCOPY | Copies the brush currently selected in hdcDest, into the destination bitmap.
PATINVERT | Combines the colors of the brush currently selected in hdcDest, with the colors of the destination rectangle by using the Boolean XOR operator.
PATPAINT | Combines the colors of the brush currently selected in hdcDest, with the colors of the inverted source rectangle by using the Boolean OR operator. The result of this operation is combined with the colors of the destination rectangle by using the Boolean OR operator.
SRCAND | Combines the colors of the source and destination rectangles by using the Boolean AND operator.
SRCCOPY | Copies the source rectangle directly to the destination rectangle.
SRCERASE | Combines the inverted colors of the destination rectangle with the colors of the source rectangle by using the Boolean AND operator.
SRCINVERT | Combines the colors of the source and destination rectangles by using the Boolean XOR operator.
SRCPAINT | Combines the colors of the source and destination rectangles by using the Boolean OR operator.
WHITENESS | Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the default physical palette.)

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If a rotation or shear transformation is in effect in the source device context, BitBlt returns an error. If other transformations exist in the source device context (and a matching transformation is not in effect in the destination device context), the rectangle in the destination device context is stretched, compressed, or rotated, as necessary.

If the color formats of the source and destination device contexts do not match, the BitBlt function converts the source color format to match the destination format.

When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.

Not all devices support the BitBlt function. For more information, see the RC_BITBLT raster capability entry in the GetDeviceCaps function as well as the following functions: MaskBlt, PlgBlt, and StretchBlt.

BitBlt returns an error if the source and destination device contexts represent different devices.

ICM: No color management is performed when blits occur.

For an example, see Capturing an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions


CreateBitmap

The CreateBitmap function creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).

HBITMAP CreateBitmap(
  int nWidth,         // bitmap width, in pixels
  int nHeight,        // bitmap height, in pixels
  UINT cPlanes,       // number of color planes
  UINT cBitsPerPel,   // number of bits to identify color
  CONST VOID *lpvBits // color data array
);

Parameters

nWidth
[in] Specifies the bitmap width, in pixels.
nHeight
[in] Specifies the bitmap height, in pixels.
cPlanes
[in] Specifies the number of color planes used by the device.
cBitsPerPel
[in] Specifies the number of bits required to identify the color of a single pixel.
lpvBits
[in] Pointer to an array of color data used to set the colors in a rectangle of pixels. Each scan line in the rectangle must be word aligned (scan lines that are not word aligned must be padded with zeros). If this parameter is NULL, the contents of the new bitmap is undefined.

Return Values

If the function succeeds, the return value is a handle to a bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can have the following value.

Value | Meaning
ERROR_INVALID_BITMAP | The calculated size of the bitmap is less than zero.

Remarks

After a bitmap is created, it can be selected into a device context by calling the SelectObject function.

The CreateBitmap function can be used to create color bitmaps. However,for performance reasons applications should use CreateBitmap to create monochrome bitmaps and CreateCompatibleBitmap to create color bitmaps. When a color bitmap returned from CreateBitmap is selected into a device context, the system must ensure that the bitmap matches the format of the device context it is being selected into. Since CreateCompatibleBitmap takes a device context, it returns a bitmap that has the same format as the specified device context. Because of this, subsequent calls to SelectObject are faster than with a color bitmap returned from CreateBitmap.

If the bitmap is monochrome, zeros represent the foreground color and ones represent the background color for the destination device context.

If an application sets the nWidth or nHeight parameters to zero, CreateBitmap returns the handle to a 1-by-1 pixel, monochrome bitmap.

When you no longer need the bitmap, call the DeleteObject function to delete it.

Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, DeleteObject, GetBitmapBits, SelectObject, SetBitmapBits


CreateBitmapIndirect

The CreateBitmapIndirect function creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).

HBITMAP CreateBitmapIndirect(
  CONST BITMAP *lpbm    // bitmap data
);

Parameters

lpbm
[in] Pointer to a BITMAP structure that contains information about the bitmap. If an application sets the bmWidth or bmHeight members to zero, CreateBitmapIndirect returns the handle to a 1-by-1 pixel, monochrome bitmap.

Return Values

If the function succeeds, the return value is a handle to the bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can have the following values.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more of the input parameters was invalid.
ERROR_NOT_ENOUGH_MEMORY | The bitmap is too big for memory to be allocated.

Remarks

After a bitmap is created, it can be selected into a device context by calling the SelectObject function.

While the CreateBitmapIndirect function can be used to create color bitmaps, for performance reasons applications should use CreateBitmapIndirect to create monochrome bitmaps and CreateCompatibleBitmap to create color bitmaps. When a color bitmap returned from CreateBitmapIndirect is selected into a device context, the system must ensure that the bitmap matches the format of the device context it is being selected into. Since CreateCompatibleBitmap takes a device context, it returns a bitmap that has the same format as the specified device context. Because of this, subsequent calls to SelectObject are faster than with a color bitmap returned from CreateBitmapIndirect.

If the bitmap is monochrome, zeros represent the foreground color and ones represent the background color for the destination device context.

When you no longer need the bitmap, call the DeleteObject function to delete it.

Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BitBlt, BITMAP, CreateBitmap, CreateCompatibleBitmap, CreateDIBitmap, DeleteObject, SelectObject


CreateCompatibleBitmap

The CreateCompatibleBitmap function creates a bitmap compatible with the device that is associated with the specified device context.

HBITMAP CreateCompatibleBitmap(
  HDC hdc,        // handle to DC
  int nWidth,     // width of bitmap, in pixels
  int nHeight     // height of bitmap, in pixels
);

Parameters

hdc
[in] Handle to a device context.
nWidth
[in] Specifies the bitmap width, in pixels.
nHeight
[in] Specifies the bitmap height, in pixels.

Return Values

If the function succeeds, the return value is a handle to the bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The color format of the bitmap created by the CreateCompatibleBitmap function matches the color format of the device identified by the hdc parameter. This bitmap can be selected into any memory device context that is compatible with the original device.

Because memory device contexts allow both color and monochrome bitmaps, the format of the bitmap returned by the CreateCompatibleBitmap function differs when the specified device context is a memory device context. However, a compatible bitmap that was created for a nonmemory device context always possesses the same color format and uses the same color palette as the specified device context.

Note: When a memory device context is created, it initially has a 1-by-1 monochrome bitmap selected into it. If this memory device context is used in CreateCompatibleBitmap, the bitmap that is created is a monochrome bitmap. To create a color bitmap, use the hDC that was used to create the memory device context, as shown in the following code:

    HDC memDC = CreateCompatibleDC ( hDC );
    HBITMAP memBM = CreateCompatibleBitmap ( hDC );
    SelectObject ( memDC, memBM );

If an application sets the nWidth or nHeight parameters to zero, CreateCompatibleBitmap returns the handle to a 1-by-1 pixel, monochrome bitmap.

If a DIB section, which is a bitmap created by the CreateDIBSection function, is selected into the device context identified by the hdc parameter, CreateCompatibleBitmap creates a DIB section.

When you no longer need the bitmap, call the DeleteObject function to delete it.

Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.

For an example, see Scaling an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, CreateDIBSection, DeleteObject, SelectObject


CreateDIBitmap

The CreateDIBitmap function creates a device-dependent bitmap (DDB) from a DIB and, optionally, sets the bitmap bits.

HBITMAP CreateDIBitmap(
  HDC hdc,                        // handle to DC
  CONST BITMAPINFOHEADER *lpbmih, // bitmap data
  DWORD fdwInit,                  // initialization option
  CONST VOID *lpbInit,            // initialization data
  CONST BITMAPINFO *lpbmi,        // color-format data
  UINT fuUsage                    // color-data usage
);

Parameters

hdc
[in] Handle to a device context.
lpbmih
[in] Pointer to a bitmap information header structure, which may be one of those shown in the following table.
Operating system | Bitmap information header
Windows NT 3.51 and earlier | BITMAPINFOHEADER
Windows NT 4.0 and Windows 95 | BITMAPV4HEADER
Windows 2000 and Windows 98 | BITMAPV5HEADER

If fdwInit is CBM_INIT, the function uses the bitmap information header structure to obtain the desired width and height of the bitmap as well as other information. Note that a positive value for the height indicates a bottom-up DIB while a negative value for the height indicates a top-down DIB. Calling CreateDIBitmap with fdwInit as CBM_INIT is equivalent to calling the CreateCompatibleBitmap function to create a DDB in the format of the device and then calling the SetDIBits function to translate the DIB bits to the DDB.

fdwInit
[in] Specifies how the system initializes the bitmap bits. The following values is defined.
Value Meaning
CBM_INIT If this flag is set, the system uses the data pointed to by the lpbInit and lpbmi parameters to initialize the bitmap's bits.

If this flag is clear, the data pointed to by those parameters is not used.

If fdwInit is zero, the system does not initialize the bitmap's bits.

lpbInit
[in] Pointer to an array of bytes containing the initial bitmap data. The format of the data depends on the biBitCount member of the BITMAPINFO structure to which the lpbmi parameter points.
lpbmi
[in] Pointer to a BITMAPINFO structure that describes the dimensions and color format of the array pointed to by the lpbInit parameter.
fuUsage
[in] Specifies whether the bmiColors member of the BITMAPINFO structure was initialized and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or palette indexes. The fuUsage parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | A color table is provided and consists of an array of 16-bit indexes into the logical palette of the device context into which the bitmap is to be selected.
DIB_RGB_COLORS | A color table is provided and contains literal RGB values.

Return Values

If the function succeeds, the return value is a handle to the bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The DDB that is created will be whatever bit depth your reference DC is. To create a bitmap that is of different bit depth, use CreateDIBSection.

For a device to reach optimal bitmap-drawing speed, specify fdwInit as CBM_INIT. Then, use the same color depth DIB as the video mode. When the video is running 4- or 8-bpp, use DIB_PAL_COLORS.

The CBM_CREATDIB flag for the fdwInit parameter is no longer supported.

When you no longer need the bitmap, call the DeleteObject function to delete it.

ICM: No color management is performed. The contents of the resulting bitmap are not color matched after the bitmap has been created.

Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BITMAPINFOHEADER, BITMAPINFO, CreateCompatibleBitmap, CreateDIBSection, DeleteObject, GetDeviceCaps, GetSystemPaletteEntries, SelectObject, SetDIBits


CreateDIBSection

The CreateDIBSection function creates a DIB that applications can write to directly. The function gives you a pointer to the location of the bitmap's bit values. You can supply a handle to a file-mapping object that the function will use to create the bitmap, or you can let the system allocate the memory for the bitmap.

HBITMAP CreateDIBSection(
  HDC hdc,                 // handle to DC
  CONST BITMAPINFO *pbmi,  // bitmap data
  UINT iUsage,             // data type indicator
  VOID **ppvBits,          // bit values
  HANDLE hSection,         // handle to file mapping object
  DWORD dwOffset           // offset to bitmap bit values
);

Parameters

hdc
[in] Handle to a device context. If the value of iUsage is DIB_PAL_COLORS, the function uses this device context's logical palette to initialize the DIB's colors.
pbmi
[in] Pointer to a BITMAPINFO structure that specifies various attributes of the DIB, including the bitmap's dimensions and colors.
iUsage
[in] Specifies the type of data contained in the bmiColors array member of the BITMAPINFO structure pointed to by pbmi (either logical palette indexes or literal RGB values). The following values are defined.
Value | Meaning
DIB_PAL_COLORS | The bmiColors member is an array of 16-bit indexes into the logical palette of the device context specified by hdc.
DIB_RGB_COLORS | The BITMAPINFO structure contains an array of literal RGB values.

ppvBits
[out] Pointer to a variable that receives a pointer to the location of the DIB's bit values.
hSection
[in] Handle to a file-mapping object that the function will use to create the DIB. This parameter can be NULL.

If hSection is not NULL, it must be a handle to a file-mapping object created by calling the CreateFileMapping function with the PAGE_READWRITE or PAGE_WRITECOPY flag. Read-only DIB sections are not supported. Handles created by other means will cause CreateDIBSection to fail.

If hSection is not NULL, the CreateDIBSection function locates the bitmap's bit values at offset dwOffset in the file-mapping object referred to by hSection. An application can later retrieve the hSection handle by calling the GetObject function with the HBITMAP returned by CreateDIBSection.

If hSection is NULL, the system allocates memory for the DIB. In this case, the CreateDIBSection function ignores the dwOffset parameter. An application cannot later obtain a handle to this memory. The dshSection member of the DIBSECTION structure filled in by calling the GetObject function will be NULL.

dwOffset
[in] Specifies the offset from the beginning of the file-mapping object referenced by hSection where storage for the bitmap's bit values is to begin. This value is ignored if hSection is NULL. The bitmap's bit values are aligned on doubleword boundaries, so dwOffset must be a multiple of the size of a DWORD.

Return Values

If the function succeeds, the return value is a handle to the newly created DIB, and *ppvBits points to the bitmap's bit values.

If the function fails, the return value is NULL, and *ppvBits is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can be the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more input parameters is invalid.

Remarks

As noted above, if hSection is NULL, the system allocates memory for the DIB. The system closes the handle to that memory when you later delete the DIB by calling the DeleteObject function. If hSection is not NULL, you must close the hSection memory handle yourself after calling DeleteObject to delete the bitmap.

You cannot paste a dibsection from one application into another application.

Windows NT/2000 or later: You need to guarantee that the GDI subsystem has completed any drawing to a bitmap created by CreateDIBSection before you draw to the bitmap yourself. Access to the bitmap must be synchronized. Do this by calling the GdiFlush function. This applies to any use of the pointer to the bitmap's bit values, including passing the pointer in calls to functions such as SetDIBits.

ICM:No color management is done.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BITMAPINFO, CreateFileMapping, DeleteObject, DIBSECTION, GetDIBColorTable, GetObject, GdiFlush, SetDIBits, SetDIBColorTable


CreateDiscardableBitmap

The CreateDiscardableBitmap function creates a discardable bitmap that is compatible with the specified device. The bitmap has the same bits-per-pixel format and the same color palette as the device. An application can select this bitmap as the current bitmap for a memory device that is compatible with the specified device.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the CreateCompatibleBitmap function.

HBITMAP CreateDiscardableBitmap(
  HDC hdc,     // handle to DC
  int nWidth,  // bitmap width
  int nHeight  // bitmap height
);

Parameters

hdc
[in] Handle to a device context.
nWidth
[in] Specifies the width, in pixels, of the bitmap.
nHeight
[in] Specifies the height, in pixels, of the bitmap.

Return Values

If the function succeeds, the return value is a handle to the bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When you no longer need the bitmap, call the DeleteObject function to delete it.

Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, CreateCompatibleBitmap, DeleteObject


ExtFloodFill

The ExtFloodFill function fills an area of the display surface with the current brush.

BOOL ExtFloodFill(
  HDC hdc,          // handle to DC
  int nXStart,      // starting x-coordinate
  int nYStart,      // starting y-coordinate
  COLORREF crColor, // fill color
  UINT fuFillType   // fill type
);

Parameters

hdc
[in] Handle to a device context.
nXStart
[in] Specifies the logical x-coordinate of the point where filling is to start.
nYStart
[in] Specifies the logical y-coordinate of the point where filling is to start.
crColor
[in] Specifies the color of the boundary or of the area to be filled. The interpretation of crColor depends on the value of the fuFillType parameter. To create a COLORREF color value, use the RGB macro.
fuFillType
[in] Specifies the type of fill operation to be performed. This parameter must be one of the following values.
Value | Meaning
FLOODFILLBORDER | The fill area is bounded by the color specified by the crColor parameter. This style is identical to the filling performed by the FloodFill function.
FLOODFILLSURFACE | The fill area is defined by the color that is 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 Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The following are some of the reasons this function might fail:

  • The filling could not be completed.
  • The specified point has the boundary color specified by the crColor parameter (if FLOODFILLBORDER was requested).
  • The specified point does not have the color specified by crColor (if FLOODFILLSURFACE was requested).
  • The point is outside the clipping region—that is, it is not visible on the device.

If the fuFillType parameter is FLOODFILLBORDER, the system assumes that the area to be filled is completely bounded by the color specified by the crColor parameter. The function begins filling at the point specified by the nXStart and nYStart parameters and continues in all directions until it reaches the boundary.

If fuFillType is FLOODFILLSURFACE, the system assumes that the area to be filled is a single color. The function begins to fill the area at the point specified by nXStart and nYStart and continues in all directions, filling all adjacent regions containing the color specified by crColor.

Only memory device contexts and devices that support raster-display operations support the ExtFloodFill function. To determine whether a device supports this technology, use the GetDeviceCaps function.

For an example, see Adding Lines and Graphs to a Menu.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, FloodFill, GetDeviceCaps, COLORREF, RGB


FloodFill

The FloodFill function fills an area of the display surface with the current brush. The area is assumed to be bounded as specified by the crFill parameter.

Note The FloodFill function is included only for compatibility with 16-bit versions of Windows. For Win32-based applications, use the ExtFloodFill function with FLOODFILLBORDER specified.

BOOL FloodFill(
  HDC hdc,          // handle to DC
  int nXStart,      // starting x-coordinate
  int nYStart,      // starting y-coordinate
  COLORREF crFill   // fill color
);

Parameters

hdc
[in] Handle to a device context.
nXStart
[in] Specifies the logical x-coordinate of the point where filling is to start.
nYStart
[in] Specifies the logical y-coordinate of the point where filling is to start.
crFill
[in] Specifies the color of the boundary or the area to be filled. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The following are reasons this function might fail:

  • The fill could not be completed.
  • The given point has the boundary color specified by the crFill parameter.
  • The given point lies outside the current clipping region—that is, it is not visible on the device.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, ExtFloodFill, COLORREF, RGB


GetBitmapBits

The GetBitmapBits function copies the bitmap bits of a specified bitmap into a buffer.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetDIBits function.

LONG GetBitmapBits(
  HBITMAP hbmp,      // handle to bitmap
  LONG cbBuffer,     // number of bytes to copy
  LPVOID lpvBits     // buffer to receive bits
);

Parameters

hbmp
[in] Handle to the bitmap of interest.
cbBuffer
[in] Specifies the number of bytes to copy from the bitmap into the buffer.
lpvBits
[out] Pointer to a buffer to receive the bitmap bits. The bits are stored as an array of byte values.

Return Values

If the function succeeds, the return value is the number of bytes copied to the buffer.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions


GetBitmapDimensionEx

The GetBitmapDimensionEx function retrieves the dimensions of a bitmap. The retrieved dimensions must have been set by the SetBitmapDimensionEx function.

BOOL GetBitmapDimensionEx(
  HBITMAP hBitmap,     // handle to bitmap
  LPSIZE lpDimension   // dimensions
);

Parameters

hBitmap
[in] Handle to the bitmap.
lpDimension
[out] Pointer to a SIZE structure to receive the bitmap dimensions.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The function returns a data structure that contains fields for the height and width of the bitmap, in .01-mm units. If those dimensions have not yet been set, the structure that is returned will have zeroes in those fields.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, SetBitmapDimensionEx, SIZE


GetDIBColorTable

The GetDIBColorTable function retrieves RGB (red, green, blue) color values from a range of entries in the color table of the DIB section bitmap that is currently selected into a specified device context.

UINT GetDIBColorTable(
  HDC hdc,           // handle to DC
  UINT uStartIndex,  // color table index of first entry
  UINT cEntries,     // number of entries to retrieve
  RGBQUAD *pColors   // array of color table entries
);

Parameters

hdc
[in] Handle to a device context. A DIB section bitmap must be selected into this device context.
uStartIndex
[in] A zero-based color table index that specifies the first color table entry to retrieve.
cEntries
[in] Specifies the number of color table entries to retrieve.
pColors
[out] Pointer to a buffer that receives an array of RGBQUAD data structures containing color information from the DIB's color table. The buffer must be large enough to contain as many RGBQUAD data structures as the value of cEntries.

Return Values

If the function succeeds, the return value is the number of color table entries that the function retrieves.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The GetDIBColorTable function should be called to retrieve the color table for DIB section bitmaps that use 1, 4, or 8 bpp. The biBitCount member of a bitmap's associated BITMAPINFOHEADER structure specifies the number of bits-per-pixel. DIB section bitmaps with a biBitCount value greater than eight do not have a color table, but they do have associated color masks. Call the GetObject function to retrieve those color masks.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BITMAPINFOHEADER, CreateDIBSection, DIBSECTION, GetObject, RGBQUAD, SetDIBColorTable


GetDIBits

The GetDIBits function retrieves the bits of the specified bitmap and copies them into a buffer using the specified format.

int GetDIBits(
  HDC hdc,           // handle to DC
  HBITMAP hbmp,      // handle to bitmap
  UINT uStartScan,   // first scan line to set
  UINT cScanLines,   // number of scan lines to copy
  LPVOID lpvBits,    // array for bitmap bits
  LPBITMAPINFO lpbi, // bitmap data buffer
  UINT uUsage        // RGB or palette index
);

Parameters

hdc
[in] Handle to the device context.
hbmp
[in] Handle to the bitmap.
uStartScan
[in] Specifies the first scan line to retrieve.
cScanLines
[in] Specifies the number of scan lines to retrieve.
lpvBits
[out] Pointer to a buffer to receive the bitmap data. If this parameter is NULL, the function passes the dimensions and format of the bitmap to the BITMAPINFO structure pointed to by the lpbi parameter.
lpbi
[in/out] Pointer to a BITMAPINFO structure that specifies the desired format for the DIB data.
uUsage
[in] Specifies the format of the bmiColors member of the BITMAPINFO structure. It must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The color table should consist of an array of 16-bit indexes into the current logical palette.
DIB_RGB_COLORS | The color table should consist of literal red, green, blue (RGB) values.

Return Values

If the lpvBits parameter is non-NULL and the function succeeds, the return value is the number of scan lines copied from the bitmap.

Windows 95/98/Me: If the lpvBits parameter is NULL and GetDIBits successfully fills the BITMAPINFO structure, the return value is the total number of scan lines in the bitmap.

Windows NT/2000 or later: If the lpvBits parameter is NULL and GetDIBits successfully fills the BITMAPINFO structure, the return value is non-zero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can be the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more input parameters is invalid.

Remarks

If the requested format for the DIB matches its internal format, the RGB values for the bitmap are copied. If the requested format doesn't match the internal format, a color table is synthesized. The following table describes the color table synthesized for each format.

Value | Meaning
1_BPP | The color table consists of a black and a white entry.
4_BPP | The color table consists of a mix of colors identical to the standard VGA palette.
8_BPP | The color table consists of a general mix of 256 colors defined by GDI. (Included in these 256 colors are the 20 colors found in the default logical palette.)
24_BPP | No color table is returned.

If the lpvBits parameter is a valid pointer, the first six members of the BITMAPINFOHEADER structure must be initialized to specify the size and format of the DIB. The scan lines must be aligned on a DWORD except for RLE compressed bitmaps.

A bottom-up DIB is specified by setting the height to a positive number, while a top-down DIB is specified by setting the height to a negative number. The bitmap's color table will be appended to the BITMAPINFO structure.

If lpvBits is NULL, GetDIBits examines the first member of the first structure pointed to by lpbi. This member must specify the size, in bytes, of a BITMAPCOREHEADER or a BITMAPINFOHEADER structure. The function uses the specified size to determine how the remaining members should be initialized.

If lpvBits is NULL and the bit count member of BITMAPINFO is initialized to zero, GetDIBits fills in a BITMAPINFOHEADER structure or BITMAPCOREHEADER without the color table. This technique can be used to query bitmap attributes.

The bitmap identified by the hbmp parameter must not be selected into a device context when the application calls this function.

The origin for a bottom-up DIB is the lower-left corner of the bitmap; the origin for a top-down DIB is the upper-left corner.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, SetDIBits


GetPixel

The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.

COLORREF GetPixel(
  HDC hdc,    // handle to DC
  int nXPos,  // x-coordinate of pixel
  int nYPos   // y-coordinate of pixel
);

Parameters

hdc
[in] Handle to the device context.
nXPos
[in] Specifies the logical x-coordinate of the pixel to be examined.
nYPos
[in] Specifies the logical y-coordinate of the pixel to be examined.

Return Values

The return value is the RGB value of the pixel. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.

Remarks

The pixel must be within the boundaries of the current clipping region.

Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, COLORREF, GetDeviceCaps, SetPixel


GetStretchBltMode

The GetStretchBltMode function retrieves the current stretching mode. The stretching mode defines how color data is added to or removed from bitmaps that are stretched or compressed when the StretchBlt function is called.

int GetStretchBltMode(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the current stretching mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions


GradientFill

The GradientFill function fills rectangle and triangle structures.

BOOL GradientFill(
  HDC hdc,                   // handle to DC
  PTRIVERTEX pVertex,        // array of vertices
  ULONG dwNumVertex,         // number of vertices
  PVOID pMesh,               // array of gradients
  ULONG dwNumMesh,           // size of gradient array
  ULONG dwMode               // gradient fill mode
);

Parameters

hdc
[in] Handle to the destination device context.
pVertex
[in] Pointer to an array of TRIVERTEX structures that each define a triangle vertex.
dwNumVertex
[in] The number of vertices in pVertex.
pMesh
[in] Array of GRADIENT_TRIANGLE structures in triangle mode, or an array of GRADIENT_RECT structures in rectangle mode.
dwNumMesh
[in] The number of elements (triangles or rectangles) in pMesh.
dwMode
[in] Specifies gradient fill mode. This parameter can be one of the following values.
Value | Meaning
GRADIENT_FILL_RECT_H | In this mode, two endpoints describe a rectangle. The rectangle is defined to have a constant color (specified by the TRIVERTEX structure) for the left and right edges. GDI interpolates the color from the left to right edge and fills the interior.
GRADIENT_FILL_RECT_V | In this mode, two endpoints describe a rectangle. The rectangle is defined to have a constant color (specified by the TRIVERTEX structure) for the top and bottom edges. GDI interpolates the color from the top to bottom edge and fills the interior.
GRADIENT_FILL_TRIANGLE | In this mode, an array of TRIVERTEX structures is passed to GDI along with a list of array indexes that describe separate triangles. GDI performs linear interpolation between triangle vertices and fills the interior. Drawing is done directly in 24- and 32-bpp modes. Dithering is performed in 16-, 8-, 4-, and 1-bpp mode.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

To add smooth shading to a triangle, call the GradientFill function with the three triangle endpoints. GDI will linearly interpolate and fill the triangle.

To add smooth shading to a rectangle, call GradientFill with the upper-left and lower-right coordinates of the rectangle. There are two shading modes used when drawing a rectangle. In horizontal mode, the rectangle is shaded from left-to-right. In vertical mode, the rectangle is shaded from top-to-bottom.

The GradientFill function uses a mesh method to specify the endpoints of the object to draw. All vertices are passed to GradientFill in the pVertex array. The pMesh parameter specifies how these vertices are connected to form an object. When filling a rectangle, pMesh points to an array of GRADIENT_RECT structures. Each GRADIENT_RECT structure specifies the index of two vertices in the pVertex array. These two vertices form the upper-left and lower-right boundary of one rectangle.

In the case of filling a triangle, pMesh points to an array of GRADIENT_TRIANGLE structures. Each GRADIENT_TRIANGLE structure specifies the index of three vertices in the pVertex array. These three vertices form one triangle.

In order to simplify hardware acceleration, this routine is not required to be pixel-perfect in the triangle interior.

For more information, see Smooth Shading, Drawing a Shaded Triangle, and Drawing a Shaded Rectangle.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Included as a resource in Msimg32.dll.

See Also

Bitmaps Overview, Bitmap Functions, EMRGRADIENTFILL, GRADIENT_RECT, GRADIENT_TRIANGLE, TRIVERTEX


LoadBitmap

The LoadBitmap function loads the specified bitmap resource from a module's executable file. This function has been superseded by the LoadImage function.

HBITMAP LoadBitmap(
  HINSTANCE hInstance,  // handle to application instance
  LPCTSTR lpBitmapName  // name of bitmap resource
);

Parameters

hInstance
[in] Handle to the instance of the module whose executable file contains the bitmap to be loaded.
lpBitmapName
[in] Pointer to a null-terminated string that contains the name of the bitmap resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. The MAKEINTRESOURCE macro can be used to create this value.

Return Values

If the function succeeds, the return value is the handle to the specified bitmap.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If the bitmap pointed to by the lpBitmapName parameter does not exist or there is insufficient memory to load the bitmap, the function fails.

LoadBitmap creates a compatible bitmap of the display, which cannot be selected to a printer. To load a bitmap that you can select to a printer, call LoadImage and specify LR_CREATEDIBSECTION to create a DIB section. A DIB section can be selected to any device.

An application can use the LoadBitmap function to access the predefined bitmaps used by the Win32 API. To do so, the application must set the hInstance parameter to NULL and the lpBitmapName parameter to one of the following values.

Bitmap name | Bitmap name
OBM_BTNCORNERS | OBM_OLD_RESTORE
OBM_BTSIZE | OBM_OLD_RGARROW
OBM_CHECK | OBM_OLD_UPARROW
OBM_CHECKBOXES | OBM_OLD_ZOOM
OBM_CLOSE | OBM_REDUCE
OBM_COMBO | OBM_REDUCED
OBM_DNARROW | OBM_RESTORE
OBM_DNARROWD | OBM_RESTORED
OBM_DNARROWI | OBM_RGARROW
OBM_LFARROW | OBM_RGARROWD
OBM_LFARROWD | OBM_RGARROWI
OBM_LFARROWI | OBM_SIZE
OBM_MNARROW | OBM_UPARROW
OBM_OLD_CLOSE | OBM_UPARROWD
OBM_OLD_DNARROW | OBM_UPARROWI
OBM_OLD_LFARROW | OBM_ZOOM
OBM_OLD_REDUCE | OBM_ZOOMD

Bitmap names that begin with OBM_OLD represent bitmaps used by 16-bit versions of Windows earlier than 3.0.

For an application to use any of the OBM_ constants, the constant OEMRESOURCE must be defined before the Windows.h header file is included.

The application must call the DeleteObject function to delete each bitmap handle returned by the LoadBitmap function.

Windows 95 has a problem dealing with Win32 .exe or .dll files that contain resources whose size is 64K or larger. To retain Win16 compatibility, Windows 95 converts the 32-bit size into a 16-bit size and a shift count. When it does this conversion it rounds down instead of up, so some bytes can be lost. In addition, Win16 uses the same shift count for all resources, thus the shift required for a large resource can cause a small resource to be severely truncated, or even eliminated completely.

To avoid this problem, compute the scaling factor for the largest resource and pad all resources with zeroes so each is a multiple of the scaling factor. For example, a resource of size 0x100065 is converted to 0x8003 * 32, which loses 5 bytes. To save the 5 bytes, you must pad the resource with 27 zeroes so that it becomes size 0x100080 and is then converted to 0x8004 * 32. Note, any smaller resource must also be padded with zeroes so it is a multiple of the scaling factor, which in this case is 32.

For an example, see Example of Menu-Item Bitmaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Bitmaps Overview, Bitmap Functions, CreateBitmap, DeleteObject, LoadCursor, LoadIcon, LoadImage, MAKEINTRESOURCE


MaskBlt

The MaskBlt function combines the color data for the source and destination bitmaps using the specified mask and raster operation.

BOOL MaskBlt(
  HDC hdcDest,     // handle to destination DC
  int nXDest,      // x-coord of destination upper-left corner
  int nYDest,      // y-coord of destination upper-left corner
  int nWidth,      // width of source and destination
  int nHeight,     // height of source and destination
  HDC hdcSrc,      // handle to source DC
  int nXSrc,       // x-coord of upper-left corner of source
  int nYSrc,       // y-coord of upper-left corner of source
  HBITMAP hbmMask, // handle to monochrome bit mask
  int xMask,       // horizontal offset into mask bitmap
  int yMask,       // vertical offset into mask bitmap
  DWORD dwRop      // raster operation code
);

Parameters

hdcDest
[in] Handle to the destination device context.
nXDest
[in] Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.
nYDest
[in] Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.
nWidth
[in] Specifies the width, in logical units, of the destination rectangle and source bitmap.
nHeight
[in] Specifies the height, in logical units, of the destination rectangle and source bitmap.
hdcSrc
[in] Handle to 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.
nXSrc
[in] Specifies the logical x-coordinate of the upper-left corner of the source bitmap.
nYSrc
[in] Specifies the logical y-coordinate of the upper-left corner of the source bitmap.
hbmMask
[in] Handle to the monochrome mask bitmap combined with the color bitmap in the source device context.
xMask
[in] Specifies the horizontal pixel offset for the mask bitmap specified by the hbmMask parameter.
yMask
[in] Specifies the vertical pixel offset for the mask bitmap specified by the hbmMask parameter.
dwRop
[in] Specifies both foreground and background ternary raster operation codes that the function uses to control the combination of source and destination data. The background raster operation code is stored in the high-order byte of the high-order word of this value; the foreground raster operation code is stored in the low-order byte of the high-order word of this value; the low-order word of this value is ignored, and should be zero. The macro MAKEROP4 creates such combinations of foreground and background raster operation codes.

For a discussion of foreground and background in the context of this function, see the following Remarks section.

For a list of common raster operation codes, see the BitBlt function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A value of 1 in the mask specified by hbmMask 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 transformation 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 FALSE) if the source device context identifies an enhanced-metafile device context.

Not all devices support the MaskBlt function. An application should call the GetDeviceCaps function 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.

ICM: No color management is performed when blits occur.

Windows 2000 or later: When used in a multimonitor system, both hdcSrc and hdcDest must refer to the same device or the function will fail.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BitBlt, GetDeviceCaps, PlgBlt, StretchBlt


PlgBlt

The PlgBlt function 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 destination device context. 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.

BOOL PlgBlt(
  HDC hdcDest,          // handle to destination DC
  CONST POINT *lpPoint, // destination vertices
  HDC hdcSrc,           // handle to source DC
  int nXSrc,            // x-coord of source upper-left corner
  int nYSrc,            // y-coord of source upper-left corner
  int nWidth,           // width of source rectangle
  int nHeight,          // height of source rectangle
  HBITMAP hbmMask,      // handle to bitmask
  int xMask,            // x-coord of bitmask upper-left corner
  int yMask             // y-coord of bitmask upper-left corner
);

Parameters

hdcDest
[in] Handle to the destination device context.
lpPoint
[in] Pointer to an array of three points in logical space that identify 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.
hdcSrc
[in] Handle to the source device context.
nXSrc
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.
nYSrc
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.
nWidth
[in] Specifies the width, in logical units, of the source rectangle.
nHeight
[in] Specifies the height, in logical units, of the source rectangle.
hbmMask
[in] Handle to an optional monochrome bitmap that is used to mask the colors of the source rectangle.
xMask
[in] Specifies the x-coordinate of the upper-left corner of the the monochrome bitmap.
yMask
[in] Specifies the y-coordinate of the upper-left corner of the the monochrome bitmap.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

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 one in the mask indicates that the source pixel color should be copied to the destination. A value of zero 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 the PlgBlt function. For more information, see the description of the RC_BITBLT raster capability in the GetDeviceCaps function.

If the source and destination device contexts represent incompatible devices, PlgBlt returns an error.

Windows 2000 or later: When used in a multimonitor system, both hdcSrc and hdcDest must refer to the same device or the function will fail.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BitBlt, GetDeviceCaps, MaskBlt, SetStretchBltMode, StretchBlt


SetBitmapBits

The SetBitmapBits function sets the bits of color data for a bitmap to the specified values.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the SetDIBits function.

LONG SetBitmapBits(
  HBITMAP hbmp,        // handle to bitmap
  DWORD cBytes,        // number of bytes in bitmap array
  CONST VOID *lpBits   // array with bitmap bits
);

Parameters

hbmp
[in] Handle to the bitmap to be set.
cBytes
[in] Specifies the number of bytes pointed to by the lpBits parameter.
lpBits
[in] Pointer to an array of bytes that contain color data for the specified bitmap.

Return Values

If the function succeeds, the return value is the number of bytes used in setting the bitmap bits.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The array identified by lpBits must be WORD aligned.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, GetBitmapBits, SetDIBits


SetBitmapDimensionEx

The SetBitmapDimensionEx function assigns preferred dimensions to a bitmap. These dimensions can be used by applications; however, they are not used by the system.

BOOL SetBitmapDimensionEx(
  HBITMAP hBitmap,  // handle to bitmap
  int nWidth,       // bitmap width in .01-mm units
  int nHeight,      // bitmap height in .01-mm units
  LPSIZE lpSize     // original dimensions
);

Parameters

hBitmap
[in] Handle to the bitmap. The bitmap cannot be a DIB-section bitmap.
nWidth
[in] Specifies the width, in 0.1-millimeter units, of the bitmap.
nHeight
[in] Specifies the height, in 0.1-millimeter units, of the bitmap.
lpSize
[out] Pointer to a SIZE structure to receive the previous dimensions of the bitmap. This pointer can be NULL.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can retrieve the dimensions assigned to a bitmap with the SetBitmapDimensionEx function by calling the GetBitmapDimensionEx function.

The bitmap identified by hBitmap cannot be a DIB section, which is a bitmap created by the CreateDIBSection function. If the bitmap is a DIB section, the SetBitmapDimensionEx function fails.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, CreateDIBSection, GetBitmapDimensionEx, SIZE


SetDIBColorTable

The SetDIBColorTable function sets RGB (red, green, blue) color values in a range of entries in the color table of the DIB that is currently selected into a specified device context.

UINT SetDIBColorTable(
  HDC hdc,               // handle to DC
  UINT uStartIndex,      // color table index of first entry
  UINT cEntries,         // number of color table entries
  CONST RGBQUAD *pColors // array of color table entries
);

Parameters

hdc
[in] Specifies a device context. A DIB must be selected into this device context.
uStartIndex
[in] A zero-based color table index that specifies the first color table entry to set.
cEntries
[in] Specifies the number of color table entries to set.
pColors
[in] Pointer to an array of RGBQUAD structures containing new color information for the DIB's color table.

Return Values

If the function succeeds, the return value is the number of color table entries that the function sets.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This function should be called to set the color table for DIBs that use 1, 4, or 8 bpp. The BitCount member of a bitmap's associated bitmap information header structure.

Note A bitmap information header structure may be one of the following.

Operating system | Bitmap information header
Windows NT 3.51 and earlier | BITMAPINFOHEADER
Windows NT 4.0 and Windows 95 | BITMAPV4HEADER
Windows 2000 and Windows 98 | BITMAPV5HEADER

BITMAPINFOHEADER structure specifies the number of bits-per-pixel. Device-independent bitmaps with a biBitCount value greater than 8 do not have a color table.

Windows NT 4.0 and Windows 95:The bV4BitCount member of a bitmap's associated BITMAPV4HEADER structure specifies the number of bits-per-pixel. Device-independent bitmaps with a bV4BitCount value greater than 8 do not have a color table.

Windows 2000 and Windows 98/Me: The bV5BitCount member of a bitmap's associated BITMAPV5HEADER structure specifies the number of bits-per-pixel. Device-independent bitmaps with a bV5BitCount value greater than 8 do not have a color table.

ICM: No color management is performed.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BITMAPINFOHEADER, CreateDIBSection, GetDIBColorTable, GetObject, DIBSECTION, RGBQUAD


SetDIBits

The SetDIBits function sets the pixels in a bitmap using the color data found in the specified DIB .

int SetDIBits(
  HDC hdc,                  // handle to DC
  HBITMAP hbmp,             // handle to bitmap
  UINT uStartScan,          // starting scan line
  UINT cScanLines,          // number of scan lines
  CONST VOID *lpvBits,      // array of bitmap bits
  CONST BITMAPINFO *lpbmi,  // bitmap data
  UINT fuColorUse           // type of color indexes to use
);

Parameters

hdc
[in] Handle to a device context.
hbmp
[in] Handle to the bitmap that is to be altered using the color data from the specified DIB.
uStartScan
[in] Specifies the starting scan line for the device-independent color data in the array pointed to by the lpvBits parameter.
cScanLines
[in] Specifies the number of scan lines found in the array containing device-independent color data.
lpvBits
[in] Pointer to the DIB color data, stored as an array of bytes. The format of the bitmap values depends on the biBitCount member of the BITMAPINFO structure pointed to by the lpbmi parameter.
lpbmi
[in] Pointer to a BITMAPINFO structure that contains information about the DIB.
fuColorUse
[in] Specifies whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or palette indexes. The fuColorUse parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The color table consists of an array of 16-bit indexes into the logical palette of the device context identified by the hdc parameter.
DIB_RGB_COLORS | The color table is provided and contains literal RGB values.

Return Values

If the function succeeds, the return value is the number of scan lines copied.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can be the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more input parameters are invalid.

Remarks

Optimal bitmap drawing speed is obtained when the bitmap bits are indexes into the system palette.

Applications can retrieve the system palette colors and indexes by calling the GetSystemPaletteEntries function. After the colors and indexes are retrieved, the application can create the DIB. For more information, see System Palette.

The device context identified by the hdc parameter is used only if the DIB_PAL_COLORS constant is set for the fuColorUse parameter; otherwise it is ignored.

The bitmap identified by the hbmp parameter must not be selected into a device context when the application calls this function.

The scan lines must be aligned on a DWORD except for RLE-compressed bitmaps.

The origin for bottom-up DIBs is the lower-left corner of the bitmap; the origin for top-down DIBs is the upper-left corner of the bitmap.

ICM: Color management is performed. The color profile of the current device context is used as the source color space profile and the sRGB color space is used.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, GetDIBits, GetSystemPaletteEntries, BITMAPINFO


SetDIBitsToDevice

The SetDIBitsToDevice function sets the pixels in the specified rectangle on the device that is associated with the destination device context using color data from a DIB.

Windows 98 and Windows 2000 or later: SetDIBitsToDevice has been extended to allow a JPEG or PNG image to be passed as the source image.

int SetDIBitsToDevice(
  HDC hdc,                 // handle to DC
  int XDest,               // x-coord of destination upper-left corner
  int YDest,               // y-coord of destination upper-left corner
  DWORD dwWidth,           // source rectangle width
  DWORD dwHeight,          // source rectangle height
  int XSrc,                // x-coord of source lower-left corner
  int YSrc,                // y-coord of source lower-left corner
  UINT uStartScan,         // first scan line in array
  UINT cScanLines,         // number of scan lines
  CONST VOID *lpvBits,     // array of DIB bits
  CONST BITMAPINFO *lpbmi, // bitmap information
  UINT fuColorUse          // RGB or palette indexes
);

Parameters

hdc
[in] Handle to the device context.
XDest
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
YDest
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
dwWidth
[in] Specifies the width, in logical units, of the DIB.
dwHeight
[in] Specifies the height, in logical units, of the DIB.
XSrc
[in] Specifies the x-coordinate, in logical units, of the lower-left corner of the DIB.
YSrc
[in] Specifies the y-coordinate, in logical units, of the lower-left corner of the DIB.
uStartScan
[in] Specifies the starting scan line in the DIB.
cScanLines
[in] Specifies the number of DIB scan lines contained in the array pointed to by the lpvBits parameter.
lpvBits
[in] Pointer to DIB color data stored as an array of bytes. For more information, see the following Remarks section.
lpbmi
[in] Pointer to a BITMAPINFO structure that contains information about the DIB.
fuColorUse
[in] Specifies whether the bmiColors member of the BITMAPINFO structure contains explicit red, green, blue (RGB) values or indexes into a palette. For more information, see the following Remarks section.

The fuColorUse parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The color table consists of an array of 16-bit indexes into the currently selected logical palette.
DIB_RGB_COLORS | The color table contains literal RGB values.

Return Values

If the function succeeds, the return value is the number of scan lines set.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Windows 98 and Windows 2000 or later: If the driver cannot support the JPEG or PNG file image passed to SetDIBitsToDevice, the function will fail and return GDI_ERROR. If failure does occur, the application must fall back on its own JPEG or PNG support to decompress the image into a bitmap, and then pass the bitmap to SetDIBitsToDevice.

Remarks

Optimal bitmap drawing speed is obtained when the bitmap bits are indexes into the system palette.

Applications can retrieve the system palette colors and indexes by calling the GetSystemPaletteEntries function. After the colors and indexes are retrieved, the application can create the DIB. For more information about the system palette, see Colors.

The origin of a bottom-up DIB is the lower-left corner of the bitmap; the origin of a top-down DIB is the upper-left corner.

To reduce the amount of memory required to set bits from a large DIB on a device surface, an application can band the output by repeatedly calling SetDIBitsToDevice, placing a different portion of the bitmap into the lpvBits array each time. The values of the uStartScan and cScanLines parameters identify the portion of the bitmap contained in the lpvBits array.

The SetDIBitsToDevice function returns an error if it is called by a process that is running in the background while a full-screen MS-DOS session runs in the foreground.

Windows 98/Me, Windows 2000 or later:

  • If the biCompression member of BITMAPINFOHEADER is BI_JPEG or BI_PNG, lpvBits points to a buffer containing a JPEG or PNG image. The biSizeImage member of specifies the size of the buffer. The fuColorUse parameter must be set to DIB_RGB_COLORS.
  • To ensure proper metafile spooling while printing, applications must call the CHECKJPEGFORMAT or CHECKPNGFORMAT escape to verify that the printer recognizes the JPEG or PNG image, respectively, before calling SetDIBitsToDevice.

ICM: Color management is performed. The color profile of the current device context is used as the source color space profile. The sRGB color space is used.

For an example, see Testing a Printer for JPEG or PNG Support.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BITMAPINFO, GetSystemPaletteEntries, SetDIBits, StretchDIBits


SetPixel

The SetPixel function sets the pixel at the specified coordinates to the specified color.

COLORREF SetPixel(
  HDC hdc,           // handle to DC
  int X,             // x-coordinate of pixel
  int Y,             // y-coordinate of pixel
  COLORREF crColor   // pixel color
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the x-coordinate, in logical units, of the point to be set.
Y
[in] Specifies the y-coordinate, in logical units, of the point to be set.
crColor
[in] Specifies the color to be used to paint the point. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value is the RGB value that the function sets the pixel to. This value may differ from the color specified by crColor; that occurs when an exact match for the specified color cannot be found.

If the function fails, the return value is –1.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can be the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more input parameters are invalid.

Remarks

The function fails if the pixel coordinates lie outside of the current clipping region.

Not all devices support the SetPixel function. For more information, see GetDeviceCaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, GetDeviceCaps, GetPixel, SetPixelV, COLORREF, RGB


SetPixelV

The SetPixelV function sets the pixel at the specified coordinates to the closest approximation of the specified color. The point must be in the clipping region and the visible part of the device surface.

BOOL SetPixelV(
  HDC hdc,           // handle to device context
  int X,             // x-coordinate of pixel
  int Y,             // y-coordinate of pixel
  COLORREF crColor   // new pixel color
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the x-coordinate, in logical units, of the point to be set.
Y
[in] Specifies the y-coordinate, in logical units, of the point to be set.
crColor
[in] Specifies the color to be used to paint the point. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Not all devices support the SetPixelV function. For more information, see the description of the RC_BITBLT capability in the GetDeviceCaps function.

SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, GetDeviceCaps, SetPixel, COLORREF, RGB


SetStretchBltMode

The SetStretchBltMode function sets the bitmap stretching mode in the specified device context.

int SetStretchBltMode(
  HDC hdc,           // handle to DC
  int iStretchMode   // bitmap stretching mode
);

Parameters

hdc
[in] Handle to the device context.
iStretchMode
[in] Specifies the stretching mode. This parameter can be one 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 SetBrushOrgEx function to set the brush origin. If it fails to do so, brush misalignment occurs.

This is not supported on Windows 95/98.
STRETCH_ANDSCANS | Same as BLACKONWHITE.
STRETCH_DELETESCANS | Same as COLORONCOLOR.
STRETCH_HALFTONE | Same as HALFTONE.
STRETCH_ORSCANS | 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 Values

If the function succeeds, the return value is the previous stretching mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError. This can be the following value.

Value | Meaning
ERROR_INVALID_PARAMETER | One or more input parameters are invalid.

Remarks

The stretching mode defines how the system combines rows or columns of a bitmap with existing pixels on a display device when an application calls the StretchBlt 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 is slower and requires more processing of the source image than the other three modes; 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, GetStretchBltMode, SetBrushOrgEx, StretchBlt


StretchBlt

The StretchBlt function copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap to fit the dimensions of the destination rectangle, if necessary. The system stretches or compresses the bitmap according to the stretching mode currently set in the destination device context.

BOOL StretchBlt(
  HDC hdcDest,      // handle to destination DC
  int nXOriginDest, // x-coord of destination upper-left corner
  int nYOriginDest, // y-coord of destination upper-left corner
  int nWidthDest,   // width of destination rectangle
  int nHeightDest,  // height of destination rectangle
  HDC hdcSrc,       // handle to source DC
  int nXOriginSrc,  // x-coord of source upper-left corner
  int nYOriginSrc,  // y-coord of source upper-left corner
  int nWidthSrc,    // width of source rectangle
  int nHeightSrc,   // height of source rectangle
  DWORD dwRop       // raster operation code
);

Parameters

hdcDest
[in] Handle to the destination device context.
nXOriginDest
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nYOriginDest
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nWidthDest
[in] Specifies the width, in logical units, of the destination rectangle.
nHeightDest
[in] Specifies the height, in logical units, of the destination rectangle.
hdcSrc
[in] Handle to the source device context.
nXOriginSrc
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.
nYOriginSrc
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.
nWidthSrc
[in] Specifies the width, in logical units, of the source rectangle.
nHeightSrc
[in] Specifies the height, in logical units, of the source rectangle.
dwRop
[in] Specifies the raster operation to be performed. Raster operation codes define how the system combines colors in output operations that involve a brush, a source bitmap, and a destination bitmap.

See BitBlt for a list of common raster operation codes.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

StretchBlt stretches or compresses the source bitmap in memory and then copies the result to the destination rectangle. The color data for pattern or destination pixels is merged after the stretching or compression occurs.

When an enhanced metafile is being recorded, an error occurs (and the function returns FALSE) if the source device context identifies an enhanced-metafile device context.

If the specified raster operation requires a brush, the system uses the brush currently selected into the destination device context.

The destination coordinates are transformed by using the transformation currently specified for the destination device context; the source coordinates are transformed by using the transformation currently specified for the source device context.

If the source transformation has a rotation or shear, an error occurs.

If destination, source, and pattern bitmaps do not have the same color format, StretchBlt converts the source and pattern bitmaps to match the destination bitmap.

If StretchBlt must convert a monochrome bitmap to a color bitmap, it sets white bits (1) to the background color and black bits (0) to the foreground color. To convert a color bitmap to a monochrome bitmap, 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.

StretchBlt creates a mirror image of a bitmap if the signs of the nWidthSrc and nWidthDest parameters or of the nHeightSrc and nHeightDest parameters differ. If nWidthSrc and nWidthDest have different signs, the function creates a mirror image of the bitmap along the x-axis. If nHeightSrc and nHeightDest have different signs, the function creates a mirror image of the bitmap along the y-axis.

Not all devices support the StretchBlt function. For more information, see the GetDeviceCaps.

ICM: No color management is performed when a blit operation occurs.

Windows 98/Me, Windows 2000 or later: When used in a multimonitor system, both hdcSrc and hdcDest must refer to the same device or the function will fail.

For an example, see Scaling an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, BitBlt, GetDeviceCaps, MaskBlt, PlgBlt, SetStretchBltMode


StretchDIBits

The StretchDIBits function copies the color data for a rectangle of pixels in a DIB to the specified destination rectangle. If the destination rectangle is larger than the source rectangle, this function stretches the rows and columns of color data to fit the destination rectangle. If the destination rectangle is smaller than the source rectangle, this function compresses the rows and columns by using the specified raster operation.

Windows 98 and Windows 2000 or later: StretchDIBits has been extended to allow a JPEG or PNG image to be passed as the source image.

int StretchDIBits(
  HDC hdc,                      // handle to DC
  int XDest,                    // x-coord of destination upper-left corner
  int YDest,                    // y-coord of destination upper-left corner
  int nDestWidth,               // width of destination rectangle
  int nDestHeight,              // height of destination rectangle
  int XSrc,                     // x-coord of source upper-left corner
  int YSrc,                     // y-coord of source upper-left corner
  int nSrcWidth,                // width of source rectangle
  int nSrcHeight,               // height of source rectangle
  CONST VOID *lpBits,           // bitmap bits
  CONST BITMAPINFO *lpBitsInfo, // bitmap data
  UINT iUsage,                  // usage options
  DWORD dwRop                   // raster operation code
);

Parameters

hdc
[in] Handle to the destination device context.
XDest
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
YDest
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nDestWidth
[in] Specifies the width, in logical units, of the destination rectangle.
nDestHeight
[in] Specifies the height, in logical units, of the destination rectangle.
XSrc
[in] Specifies the x-coordinate, in pixels, of the source rectangle in the DIB.
YSrc
[in] Specifies the y-coordinate, in pixels, of the source rectangle in the DIB.
nSrcWidth
[in] Specifies the width, in pixels, of the source rectangle in the DIB.
nSrcHeight
[in] Specifies the height, in pixels, of the source rectangle in the DIB.
lpBits
[in] Pointer to the DIB bits, which are stored as an array of bytes. For more information, see the Remarks section.
lpBitsInfo
[in] Pointer to a BITMAPINFO structure that contains information about the DIB.
iUsage
[in] Specifies whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indexes. The iUsage parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The array contains 16-bit indexes into the logical palette of the source device context.
DIB_RGB_COLORS | The color table contains literal RGB values.

For more information, see the Remarks section.

dwRop
[in] Specifies how the source pixels, the destination device context's current brush, and the destination pixels are to be combined to form the new image. For more information, see the following Remarks section.

Return Values

If the function succeeds, the return value is the number of scan lines copied.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Windows 98/Windows 2000 or later: If the driver cannot support the JPEG or PNG file image passed to StretchDIBits, the function will fail and return GDI_ERROR. If failure does occur, the application must fall back on its own JPEG or PNG support to decompress the image into a bitmap, and then pass the bitmap to StretchDIBits.

Remarks

The origin of a bottom-up DIB is the bottom-left corner; the origin of a top-down DIB is the upper-left corner.

StretchDIBits creates a mirror image of a bitmap if the signs of the nSrcWidth and nDestWidth parameters, or if the nSrcHeight and nDestHeight parameters differ. If nSrcWidth and nDestWidth have different signs, the function creates a mirror image of the bitmap along the x-axis. If nSrcHeight and nDestHeight have different signs, the function creates a mirror image of the bitmap along the y-axis.

Windows 98/Windows 2000 or later: This function allows a JPEG or PNG image to be passed as the source image. How each parameter is used remains the same, except :

  • If the biCompression member of BITMAPINFOHEADER is BI_JPEG or BI_PNG, lpBits points to a buffer containing a JPEG or PNG image, respectively. The BITMAPINFOHEADER's biSizeImage member specifies the size of the buffer. The iUsage parameter must be set to DIB_RGB_COLORS. The dwRop parameter must be set to SRCCOPY.
  • To ensure proper metafile spooling while printing, applications must call the CHECKJPEGFORMAT or CHECKPNGFORMAT escape to verify that the printer recognizes the JPEG or PNG image, respectively, before calling StretchDIBits.

ICM: Color management is performed. The color profile of the current device context is used as the source color space profile and the sRGB space is used.

For an example, see Sizing a JPEG or PNG Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, SetMapMode, SetStretchBltMode, BITMAPINFO


TransparentBlt

The TransparentBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context.

BOOL TransparentBlt(
  HDC hdcDest,        // handle to destination DC
  int nXOriginDest,   // x-coord of destination upper-left corner
  int nYOriginDest,   // y-coord of destination upper-left corner
  int nWidthDest,     // width of destination rectangle
  int hHeightDest,    // height of destination rectangle
  HDC hdcSrc,         // handle to source DC
  int nXOriginSrc,    // x-coord of source upper-left corner
  int nYOriginSrc,    // y-coord of source upper-left corner
  int nWidthSrc,      // width of source rectangle
  int nHeightSrc,     // height of source rectangle
  UINT crTransparent  // color to make transparent
);

Parameters

hdcDest
[in] Handle to the destination device context.
nXOriginDest
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nYOriginDest
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
nWidthDest
[in] Specifies the width, in logical units, of the destination rectangle.
hHeightDest
[in] Handle to the height, in logical units, of the destination rectangle.
hdcSrc
[in] Handle to the source device context.
nXOriginSrc
[in] Specifies the x-coordinate, in logical units, of the source rectangle.
nYOriginSrc
[in] Specifies the y-coordinate, in logical units, of the source rectangle.
nWidthSrc
[in] Specifies the width, in logical units, of the source rectangle.
nHeightSrc
[in] Specifies the height, in logical units, of the source rectangle.
crTransparent
[in] The RGB color in the source bitmap to treat as transparent.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The TransparentBlt function supports all formats of source bitmaps. However, for 32 bpp bitmaps, it just copies the alpha value over. Use AlphaBlend to specify 32 bits-per-pixel bitmaps with transparency.

If the source and destination rectangles are not the same size, the source bitmap is stretched to match the destination rectangle. When the SetStretchBltMode function is used, the iStretchMode modes of BLACKONWHITE and WHITEONBLACK are converted to COLORONCOLOR for the TransparentBlt function.

The destination device context specifies the transformation type for the destination coordinates. The source device context specifies the transformation type for the source coordinates.

TransparentBlt does not mirror a bitmap if either the width or height, of either the source or destination, is negative.

Windows 98/Windows 2000 or later: When used in a multimonitor system, both hdcSrc and hdcDest must refer to the same device or the function will fail.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Bitmaps Overview, Bitmap Functions, AlphaBlend, SetStretchBltMode


Bitmap Structures

The following structures are used with bitmaps.

BITMAP
BITMAPCOREHEADER
BITMAPCOREINFO
BITMAPFILEHEADER
BITMAPINFO
BITMAPINFOHEADER
BITMAPV4HEADER
BITMAPV5HEADER
BLENDFUNCTION
COLORADJUSTMENT
DIBSECTION
GRADIENT_RECT
GRADIENT_TRIANGLE
RGBQUAD
RGBTRIPLE
SIZE
TRIVERTEX


BITMAP

The BITMAP structure defines the type, width, height, color format, and bit values of a bitmap.

typedef struct tagBITMAP {
  LONG   bmType;
  LONG   bmWidth;
  LONG   bmHeight;
  LONG   bmWidthBytes;
  WORD   bmPlanes;
  WORD   bmBitsPixel;
  LPVOID bmBits;
} BITMAP, *PBITMAP;

Members

bmType
Specifies the bitmap type. This member must be zero.
bmWidth
Specifies the width, in pixels, of the bitmap. The width must be greater than zero.
bmHeight
Specifies the height, in pixels, of the bitmap. The height must be greater than zero.
bmWidthBytes
Specifies the number of bytes in each scan line. This value must be divisible by 2, because the system assumes that the bit values of a bitmap form an array that is word aligned.
bmPlanes
Specifies the count of color planes.
bmBitsPixel
Specifies the number of bits required to indicate the color of a pixel.
bmBits
Pointer to the location of the bit values for the bitmap. The bmBits member must be a long pointer to an array of character (1-byte) values.

Remarks

The bitmap formats currently used are monochrome and color. The monochrome bitmap uses a one-bit, one-plane format. Each scan is a multiple of 32 bits.

Scans are organized as follows for a monochrome bitmap of height n:

    Scan 0
    Scan 1
    .
    .
    .
    Scan n-2
    Scan n-1

The pixels on a monochrome device are either black or white. If the corresponding bit in the bitmap is 1, the pixel is set to the foreground color; if the corresponding bit in the bitmap is zero, the pixel is set to the background color.

All devices that have the RC_BITBLT device capability support bitmaps. For more information, see GetDeviceCaps.

Each device has a unique color format. To transfer a bitmap from one device to another, use the GetDIBits and SetDIBits functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, CreateBitmapIndirect, GetDeviceCaps, GetDIBits, GetObject, SetDIBits


BITMAPCOREHEADER

The BITMAPCOREHEADER structure contains information about the dimensions and color format of a DIB.

typedef struct tagBITMAPCOREHEADER {
  DWORD   bcSize;
  WORD    bcWidth;
  WORD    bcHeight;
  WORD    bcPlanes;
  WORD    bcBitCount;
} BITMAPCOREHEADER, *PBITMAPCOREHEADER;

Members

bcSize
Specifies the number of bytes required by the structure.
bcWidth
Specifies the width of the bitmap, in pixels.
bcHeight
Specifies the height of the bitmap, in pixels.
bcPlanes
Specifies the number of planes for the target device. This value must be 1.
bcBitCount
Specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24.

Remarks

The BITMAPCOREINFO structure combines the BITMAPCOREHEADER structure and a color table to provide a complete definition of the dimensions and colors of a DIB. For more information about specifying a DIB, see BITMAPCOREINFO.

An application should use the information stored in the bcSize member to locate the color table in a BITMAPCOREINFO structure, using a method such as the following:

pColor = ((LPBYTE) pBitmapCoreInfo +
        (WORD) (pBitmapCoreInfo -> bcSize))

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPCOREINFO


BITMAPCOREINFO

The BITMAPCOREINFO structure defines the dimensions and color information for a DIB.

typedef struct _BITMAPCOREINFO {
  BITMAPCOREHEADER  bmciHeader;
  RGBTRIPLE         bmciColors[1];
} BITMAPCOREINFO, *PBITMAPCOREINFO;

Members

bmciHeader
Specifies a BITMAPCOREHEADER structure that contains information about the dimensions and color format of a DIB.
bmciColors
Specifies an array of RGBTRIPLE structures that define the colors in the bitmap.

Remarks

A DIB consists of two parts: a BITMAPCOREINFO structure describing the dimensions and colors of the bitmap, and an array of bytes defining the pixels of the bitmap. The bits in the array are packed together, but each scan line must be padded with zeroes to end on a LONG boundary. The origin of the bitmap is the lower-left corner.

The bcBitCount member of the BITMAPCOREHEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member can be one of the following values.

Value | Meaning
1 | The bitmap is monochrome, and the bmciColors member contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmciColors table; if the bit is set, the pixel has the color of the second entry in the table.
4 | The bitmap has a maximum of 16 colors, and the bmciColors member contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8 | The bitmap has a maximum of 256 colors, and the bmciColors member contains up to 256 entries. In this case, each byte in the array represents a single pixel.
24 | The bitmap has a maximum of 2 (24) colors, and the bmciColors member is NULL. Each three-byte triplet in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel.

The colors in the bmciColors table should appear in order of importance.

Alternatively, for functions that use DIBs, the bmciColors member can be an array of 16-bit unsigned integers that specify indexes into the currently realized logical palette, instead of explicit RGB values. In this case, an application using the bitmap must call the DIB functions (CreateDIBitmap, CreateDIBPatternBrush, and CreateDIBSection) with the iUsage parameter set to DIB_PAL_COLORS.

Note The bmciColors member should not contain palette indexes if the bitmap is to be stored in a file or transferred to another application. Unless the application has exclusive use and control of the bitmap, the bitmap color table should contain explicit RGB values.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPCOREHEADER, CreateDIBitmap, CreateDIBPatternBrush, CreateDIBSection, RGBTRIPLE


BITMAPFILEHEADER

The BITMAPFILEHEADER structure contains information about the type, size, and layout of a file that contains a DIB.

typedef struct tagBITMAPFILEHEADER {
  WORD    bfType;
  DWORD   bfSize;
  WORD    bfReserved1;
  WORD    bfReserved2;
  DWORD   bfOffBits;
} BITMAPFILEHEADER, *PBITMAPFILEHEADER;

Members

bfType
Specifies the file type, must be BM.
bfSize
Specifies the size, in bytes, of the bitmap file.
bfReserved1
Reserved; must be zero.
bfReserved2
Reserved; must be zero.
bfOffBits
Specifies the offset, in bytes, from the BITMAPFILEHEADER structure to the bitmap bits.

Remarks

A BITMAPINFO or BITMAPCOREINFO structure immediately follows the BITMAPFILEHEADER structure in the DIB file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPCOREINFO, BITMAPINFO


BITMAPINFO

The BITMAPINFO structure defines the dimensions and color information for a Win32 DIB.

typedef struct tagBITMAPINFO {
  BITMAPINFOHEADER bmiHeader;
  RGBQUAD          bmiColors[1];
} BITMAPINFO, *PBITMAPINFO;

Members

bmiHeader
Specifies a BITMAPINFOHEADER structure that contains information about the dimensions of color format.

.

bmiColors
The bmiColors member contains one of the following:
  • An array of RGBQUAD. The elements of the array that make up the color table.
  • An array of 16-bit unsigned integers that specifies indexes into the currently realized logical palette. This use of bmiColors is allowed for functions that use DIBs. When bmiColors elements contain indexes to a realized logical palette, they must also call the following bitmap functions:

    CreateDIBitmap

    CreateDIBPatternBrush

    CreateDIBSection

    The iUsage parameter of CreateDIBSection must be set to DIB_PAL_COLORS.

The number of entries in the array depends on the values of the biBitCount and biClrUsed members of the BITMAPINFOHEADER structure.

The colors in the bmiColors table appear in order of importance. For more information, see the Remarks section.

Remarks

A DIB consists of two distinct parts: a BITMAPINFO structure describing the dimensions and colors of the bitmap, and an array of bytes defining the pixels of the bitmap. The bits in the array are packed together, but each scan line must be padded with zeroes to end on a LONG data-type boundary. If the height of the bitmap is positive, the bitmap is a bottom-up DIB and its origin is the lower-left corner. If the height is negative, the bitmap is a top-down DIB and its origin is the upper left corner.

A bitmap is packed when the bitmap array immediately follows the BITMAPINFO header. Packed bitmaps are referenced by a single pointer. For packed bitmaps, the ClrUsed member must be set to an even number when using the DIB_PAL_COLORS mode so that the DIB bitmap array starts on a DWORD boundary.

Note The bmiColors member should not contain palette indexes if the bitmap is to be stored in a file or transferred to another application.

Unless the application has exclusive use and control of the bitmap, the bitmap color table should contain explicit RGB values.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPINFOHEADER, CreateDIBitmap, CreateDIBPatternBrush, CreateDIBSection, RGBQUAD


BITMAPINFOHEADER

The BITMAPINFOHEADER structure contains information about the dimensions and color format of a DIB.

Applications developed for Windows NT 4.0 and Windows 95 may use the BITMAPV4HEADER structure. Applications developed for Windows 2000 and Windows 98 may use the BITMAPV5HEADER structure for increased functionality. However, these are used only in the CreateDIBitmap function.

typedef struct tagBITMAPINFOHEADER{
  DWORD  biSize;
  LONG   biWidth;
  LONG   biHeight;
  WORD   biPlanes;
  WORD   biBitCount;
  DWORD  biCompression;
  DWORD  biSizeImage;
  LONG   biXPelsPerMeter;
  LONG   biYPelsPerMeter;
  DWORD  biClrUsed;
  DWORD  biClrImportant;
} BITMAPINFOHEADER, *PBITMAPINFOHEADER;

Members

biSize
Specifies the number of bytes required by the structure.
biWidth
Specifies the width of the bitmap, in pixels.

Windows 98/Me, Windows 2000 or later: If biCompression is BI_JPEG or BI_PNG, the biWidth member specifies the width of the decompressed JPEG or PNG image file, respectively.

biHeight
Specifies the height of the bitmap, in pixels. If biHeight is positive, the bitmap is a bottom-up DIB and its origin is the lower-left corner. If biHeight is negative, the bitmap is a top-down DIB and its origin is the upper-left corner.

If biHeight is negative, indicating a top-down DIB, biCompression must be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.

Windows 98/Me, Windows 2000 or later: If biCompression is BI_JPEG or BI_PNG, the biHeight member specifies the height of the decompressed JPEG or PNG image file, respectively.

biPlanes
Specifies the number of planes for the target device. This value must be set to 1.
biBitCount
Specifies the number of bits-per-pixel. The biBitCount member of the BITMAPINFOHEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member must be one of the following values.
Value | Meaning
0 | Windows 98/Me, Windows 2000 or later: The number of bits-per-pixel is specified or is implied by the JPEG or PNG format.
1 | The bitmap is monochrome, and the bmiColors member of BITMAPINFO contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmiColors table; if the bit is set, the pixel has the color of the second entry in the table.
4 | The bitmap has a maximum of 16 colors, and the bmiColors member of BITMAPINFO contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8 | The bitmap has a maximum of 256 colors, and the bmiColors member of BITMAPINFO contains up to 256 entries. In this case, each byte in the array represents a single pixel.
16 The bitmap has a maximum of 2^16 colors. If the biCompression member of the BITMAPINFOHEADER is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each WORD in the bitmap array represents a single pixel. The relative intensities of red, green, and blue are represented with five bits for each color component. The value for blue is in the least significant five bits, followed by five bits each for green and red. The most significant bit is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the biClrUsed member of the BITMAPINFOHEADER.

If the biCompression member of the BITMAPINFOHEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. Each WORD in the bitmap array represents a single pixel.

Windows NT/Windows 2000 or later: When the biCompression member is BI_BITFIELDS, bits set in each DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not have to be used.

Windows 95/98/Me: When the biCompression member is BI_BITFIELDS, the system supports only the following 16bpp color masks: A 5-5-5 16-bit image, where the blue mask is 0x001F, the green mask is 0x03E0, and the red mask is 0x7C00; and a 5-6-5 16-bit image, where the blue mask is 0x001F, the green mask is 0x07E0, and the red mask is 0xF800.
24 | The bitmap has a maximum of 2^24 colors, and the bmiColors member of BITMAPINFO is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the biClrUsed member of the BITMAPINFOHEADER.
32 The bitmap has a maximum of 2^32 colors. If the biCompression member of the BITMAPINFOHEADER is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each DWORD in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The high byte in each DWORD is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the biClrUsed member of the BITMAPINFOHEADER.

If the biCompression member of the BITMAPINFOHEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. Each DWORD in the bitmap array represents a single pixel.

Windows NT/ 2000: When the biCompression member is BI_BITFIELDS, bits set in each DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not need to be used.

Windows 95/98/Me: When the biCompression member is BI_BITFIELDS, the system supports only the following 32-bpp color mask: The blue mask is 0x000000FF, the green mask is 0x0000FF00, and the red mask is 0x00FF0000.

biCompression
Specifies the type of compression for a compressed bottom-up bitmap (top-down DIBs cannot be compressed). This member can be one of the following values.
Value | Description
BI_RGB | An uncompressed format.
BI_RLE8 | A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format is a 2-byte format consisting of a count byte followed by a byte containing a color index. For more information, see Bitmap Compression.
BI_RLE4 | An RLE format for bitmaps with 4 bpp. The compression format is a 2-byte format consisting of a count byte followed by two word-length color indexes. For more information, see Bitmap Compression.
BI_BITFIELDS | Specifies that the bitmap is not compressed and that the color table consists of three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. This is valid when used with 16- and 32-bpp bitmaps.
BI_JPEG | Windows 98/Me, Windows 2000 or later: Indicates that the image is a JPEG image.
BI_PNG | Windows 98/Me, Windows 2000 or later: Indicates that the image is a PNG image.

biSizeImage
Specifies the size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps.

Windows 98/Me, Windows 2000 or later: If biCompression is BI_JPEG or BI_PNG, biSizeImage indicates the size of the JPEG or PNG image buffer, respectively.

biXPelsPerMeter
Specifies the horizontal resolution, in pixels-per-meter, of the target device for the bitmap. An application can use this value to select a bitmap from a resource group that best matches the characteristics of the current device.
biYPelsPerMeter
Specifies the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
biClrUsed
Specifies the number of color indexes in the color table that are actually used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member for the compression mode specified by biCompression.

If biClrUsed is nonzero and the biBitCount member is less than 16, the biClrUsed member specifies the actual number of colors the graphics engine or device driver accesses. If biBitCount is 16 or greater, the biClrUsed member specifies the size of the color table used to optimize performance of the system color palettes. If biBitCount equals 16 or 32, the optimal color palette starts immediately following the three DWORD masks.

When the bitmap array immediately follows the BITMAPINFO structure, it is a packed bitmap. Packed bitmaps are referenced by a single pointer. Packed bitmaps require that the biClrUsed member must be either zero or the actual size of the color table.

biClrImportant
Specifies the number of color indexes that are required for displaying the bitmap. If this value is zero, all colors are required.

Remarks

The BITMAPINFO structure combines the BITMAPINFOHEADER structure and a color table to provide a complete definition of the dimensions and colors of a DIB. For more information about DIBs, see Device-Independent Bitmaps and BITMAPINFO.

An application should use the information stored in the biSize member to locate the color table in a BITMAPINFO structure, as follows:

pColor = ((LPSTR)pBitmapInfo + (WORD)(pBitmapInfo->bmiHeader.biSize));

Windows 98/Me, Windows 2000 or later: The BITMAPINFOHEADER structure is extended to allow a JPEG or PNG image to be passed as the source image to StretchDIBits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPINFO, BITMAPV4HEADER, BITMAPV5HEADER, CreateDIBitmap , StretchDIBits


BITMAPV4HEADER

The BITMAPV4HEADER structure is the bitmap information header file introduced in Windows 95 and Windows NT 4.0. This is used only in CreateDIBitmap.

Applications written for earlier versions of Windows and Windows NT should continue to use BITMAPINFOHEADER. Applications written for Windows 2000 and Windows 98 can use BITMAPV5HEADER.

typedef struct {
  DWORD        bV4Size;
  LONG         bV4Width;
  LONG         bV4Height;
  WORD         bV4Planes;
  WORD         bV4BitCount;
  DWORD        bV4V4Compression;
  DWORD        bV4SizeImage;
  LONG         bV4XPelsPerMeter;
  LONG         bV4YPelsPerMeter;
  DWORD        bV4ClrUsed;
  DWORD        bV4ClrImportant;
  DWORD        bV4RedMask;
  DWORD        bV4GreenMask;
  DWORD        bV4BlueMask;
  DWORD        bV4AlphaMask;
  DWORD        bV4CSType;
  CIEXYZTRIPLE bV4Endpoints;
  DWORD        bV4GammaRed;
  DWORD        bV4GammaGreen;
  DWORD        bV4GammaBlue;
} BITMAPV4HEADER, *PBITMAPV4HEADER;

Members

bV4Size
Specifies the number of bytes required by the structure. Applications should use this member to determine which bitmap information header structure is being used.
bV4Width
Specifies the width of the bitmap, in pixels.

Windows 98/Me, Windows 2000 or later: If bV4Compression is BI_JPEG or BI_PNG, bV4Width specifies the width of the JPEG or PNG image in pixels.

bV4Height
Specifies the height of the bitmap, in pixels. If bV4Height is positive, the bitmap is a bottom-up DIB and its origin is the lower-left corner. If bV4Height is negative, the bitmap is a top-down DIB and its origin is the upper-left corner.

If bV4Height is negative, indicating a top-down DIB, bV4Compression must be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.

Windows 98/Me, Windows 2000 or later: If bV4Compression is BI_JPEG or BI_PNG, bV4Height specifies the height of the JPEG or PNG image in pixels.

bV4Planes
Specifies the number of planes for the target device. This value must be set to 1.
bV4BitCount
Specifies the number of bits-per-pixel. The bV4BitCount member of the BITMAPV4HEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member must be one of the following values.
Value | Meaning
0 | Windows 98/Me, Windows 2000 or later: The number of bits-per-pixel is specified or is implied by the JPEG or PNG file format.
1 | The bitmap is monochrome, and the bmiColors member of BITMAPINFO contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmiColors table; if the bit is set, the pixel has the color of the second entry in the table.
4 | The bitmap has a maximum of 16 colors, and the bmiColors member of BITMAPINFO contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8 | The bitmap has a maximum of 256 colors, and the bmiColors member of BITMAPINFO contains up to 256 entries. In this case, each byte in the array represents a single pixel.
16 The bitmap has a maximum of 2^16 colors. If the bV4Compression member of the BITMAPV4HEADER structure is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each WORD in the bitmap array represents a single pixel. The relative intensities of red, green, and blue are represented with five bits for each color component. The value for blue is in the least significant five bits, followed by five bits each for green and red, respectively. The most significant bit is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the bV4ClrUsed member of the BITMAPV4HEADER.

If the bV4Compression member of the BITMAPV4HEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components of each pixel. Each WORD in the bitmap array represents a single pixel.
24 | The bitmap has a maximum of 2^24 colors, and the bmiColors member of BITMAPINFO is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue, green, and red for a pixel. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the bV4ClrUsed member of the BITMAPV4HEADER.
32 The bitmap has a maximum of 2^32 colors. If the bV4Compression member of the BITMAPV4HEADER is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each DWORD in the bitmap array represents the relative intensities of blue, green, and red for a pixel. The high byte in each DWORD is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the biClrUsed member of the BITMAPV4HEADER.

If the bV4Compression member of the BITMAPV4HEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components of each pixel. Each DWORD in the bitmap array represents a single pixel.

bV4V4Compression
Specifies the type of compression for a compressed bottom-up bitmap (top-down DIBs cannot be compressed). This member can be one of the following values.
Value | Description
BI_RGB | An uncompressed format.
BI_RLE8 | A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format is a 2-byte format consisting of a count byte followed by a byte containing a color index. For more information, see Bitmap Compression.
BI_RLE4 | An RLE format for bitmaps with 4 bpp. The compression format is a 2-byte format consisting of a count byte followed by two word-length color indexes. For more information, see Bitmap Compression.
BI_BITFIELDS | Specifies that the bitmap is not compressed. The members bV4RedMask, bV4GreenMask, and bV4BlueMask specify the red, green, and blue components for each pixel. This is valid when used with 16- and 32-bpp bitmaps.
BI_JPEG | Windows 98/Me, Windows 2000 or later: Specifies that the image is compressed using the JPEG file interchange format. JPEG compression trades off compression against loss; it can achieve a compression ratio of 20:1 with little noticeable loss.
BI_PNG | Windows 98/Me, Windows 2000 or later: Specifies that the image is compressed using the PNG file interchange format.

bV4SizeImage
Specifies the size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps.

Windows 98/Me, Windows 2000 or later: If bV4Compression is BI_JPEG or BI_PNG, bV4SizeImage is the size of the JPEG or PNG image buffer.

bV4XPelsPerMeter
Specifies the horizontal resolution, in pixels-per-meter, of the target device for the bitmap. An application can use this value to select a bitmap from a resource group that best matches the characteristics of the current device.
bV4YPelsPerMeter
Specifies the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
bV4ClrUsed
Specifies the number of color indexes in the color table that are actually used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the bV4BitCount member for the compression mode specified by bV4Compression.

If bV4ClrUsed is nonzero and the bV4BitCount member is less than 16, the bV4ClrUsed member specifies the actual number of colors the graphics engine or device driver accesses. If bV4BitCount is 16 or greater, the bV4ClrUsed member specifies the size of the color table used to optimize performance of the system color palettes. If bV4BitCount equals 16 or 32, the optimal color palette starts immediately following the BITMAPV4HEADER.

bV4ClrImportant
Specifies the number of color indexes that are required for displaying the bitmap. If this value is zero, all colors are important.
bV4RedMask
Color mask that specifies the red component of each pixel, valid only if bV4Compression is set to BI_BITFIELDS.
bV4GreenMask
Color mask that specifies the green component of each pixel, valid only if bV4Compression is set to BI_BITFIELDS.
bV4BlueMask
Color mask that specifies the blue component of each pixel, valid only if bV4Compression is set to BI_BITFIELDS.
bV4AlphaMask
Color mask that specifies the alpha component of each pixel.
bV4CSType
Specifies the color space of the DIB. The following table lists the value for bV4CSType.
Value | Meaning
LCS_CALIBRATED_RGB | This value indicates that endpoints and gamma values are given in the appropriate fields.

See the LOGCOLORSPACE structure for information that defines a logical color space.

bV4Endpoints
A CIEXYZTRIPLE structure that specifies the x, y, and z coordinates of the three colors that correspond to the red, green, and blue endpoints for the logical color space associated with the bitmap. This member is ignored unless the bV4CSType member specifies LCS_CALIBRATED_RGB.

Note A color space is a model for representing color numerically in terms of three or more coordinates. For example, the RGB color space represents colors in terms of the red, green, and blue coordinates.

bV4GammaRed
Toned response curve for red. This member is ignored unless color values are calibrated RGB values and bV4CSType is set to LCS_CALIBRATED_RGB. Specified in 16^16 format.
bV4GammaGreen
Toned response curve for green. Used if bV4CSType is set to LCS_CALIBRATED_RGB. Specified as 16^16 format.
bV4GammaBlue
Toned response curve for blue. Used if bV4CSType is set to LCS_CALIBRATED_RGB. Specified as 16^16 format.

Remarks

Windows 98/Me, Windows 2000 or later: The BITMAPV4HEADER structure is extended to allow a JPEG or PNG image to be passed as the source image to StretchDIBits.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPINFO, BITMAPINFOHEADER, BITMAPV5HEADER, CIEXYZTRIPLE, CreateDIBitmap, LOGCOLORSPACE, StretchDIBits


BITMAPV5HEADER

The BITMAPV5HEADER structure is the bitmap information header file introduced in Windows 2000 and Windows 98. This is only used in CreateDIBitmap. The Independent Color Management interface (ICM) 2.0 allows International Color Consortium (ICC) color profiles to be linked or embedded in DIBs (DIBs). See Using Structures in ICM 2.0 for more information.

Applications written for Windows NT 4.0 and Windows 95 can use the BITMAPV4HEADER structure. Applications written for earlier versions of Windows and Windows NT should continue to use the BITMAPINFOHEADER structure.

The BITMAPV5HEADER is an extended version of BITMAPINFOHEADER and allows a JPEG or PNG image to be passed as the source image to StretchDIBits.

typedef struct {
  DWORD        bV5Size;
  LONG         bV5Width;
  LONG         bV5Height;
  WORD         bV5Planes;
  WORD         bV5BitCount;
  DWORD        bV5Compression;
  DWORD        bV5SizeImage;
  LONG         bV5XPelsPerMeter;
  LONG         bV5YPelsPerMeter;
  DWORD        bV5ClrUsed;
  DWORD        bV5ClrImportant;
  DWORD        bV5RedMask;
  DWORD        bV5GreenMask;
  DWORD        bV5BlueMask;
  DWORD        bV5AlphaMask;
  DWORD        bV5CSType;
  CIEXYZTRIPLE bV5Endpoints;
  DWORD        bV5GammaRed;
  DWORD        bV5GammaGreen;
  DWORD        bV5GammaBlue;
  DWORD        bV5Intent;
  DWORD        bV5ProfileData;
  DWORD        bV5ProfileSize;
  DWORD        bV5Reserved;
} BITMAPV5HEADER, *PBITMAPV5HEADER;

Members

bV5Size
Specifies the number of bytes required by the structure. Applications should use this member to determine which bitmap information header structure is being used.
bV5Width
Specifies the width of the bitmap, in pixels.

If bV5Compression is BI_JPEG or BI_PNG, the bV5Width member specifies the width of the decompressed JPEG or PNG image in pixels.

bV5Height
Specifies the height of the bitmap, in pixels. If the value of bV5Height is positive, the bitmap is a bottom-up DIB and its origin is the lower-left corner. If bV5Height value is negative, the bitmap is a top-down DIB and its origin is the upper-left corner.

If bV5Height is negative, indicating a top-down DIB, bV5Compression must be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.

If bV5Compression is BI_JPEG or BI_PNG, the bV5Height member specifies the height of the decompressed JPEG or PNG image in pixels.

bV5Planes
Specifies the number of planes for the target device. This value must be set to 1.
bV5BitCount
Specifies the number of bits that define each pixel and the maximum number of colors in the bitmap.

This member can be one of the following values.
Value | Meaning
0 | The number of bits per pixel is specified or is implied by the JPEG or PNG file format.
1 | The bitmap is monochrome, and the bmiColors member of BITMAPINFO contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmiColors color table. If the bit is set, the pixel has the color of the second entry in the table.
4 | The bitmap has a maximum of 16 colors, and the bmiColors member of BITMAPINFO contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.
8 | The bitmap has a maximum of 256 colors, and the bmiColors member of BITMAPINFO contains up to 256 entries. In this case, each byte in the array represents a single pixel.
16 The bitmap has a maximum of 2^16 colors. If the bV5Compression member of the BITMAPV5HEADER structure is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each WORD in the bitmap array represents a single pixel. The relative intensities of red, green, and blue are represented with five bits for each color component. The value for blue is in the least significant five bits, followed by five bits each for green and red. The most significant bit is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the bV5ClrUsed member of the BITMAPV5HEADER.

If the bV5Compression member of the BITMAPV5HEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. Each WORD in the bitmap array represents a single pixel.

When the bV5iCompression member is BI_BITFIELDS, bits set in each DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not need to be used.

24 | The bitmap has a maximum of 2^24 colors, and the bmiColors member of BITMAPINFO is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the bV5ClrUsed member of the BITMAPV5HEADER structure.
32 The bitmap has a maximum of 2^32 colors. If the bV5Compression member of the BITMAPV5HEADER is BI_RGB, the bmiColors member of BITMAPINFO is NULL. Each DWORD in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The high byte in each DWORD is not used. The bmiColors color table is used for optimizing colors used on palette-based devices, and must contain the number of entries specified by the bV5ClrUsed member of the BITMAPV5HEADER.

If the bV5Compression member of the BITMAPV5HEADER is BI_BITFIELDS, the bmiColors member contains three DWORD color masks that specify the red, green, and blue components of each pixel. Each DWORD in the bitmap array represents a single pixel.

bV5Compression
Specifies that the bitmap is not compressed. The bV5RedMask, bV5GreenMask, and bV5BlueMask members specify the red, green, and blue components of each pixel. This is valid when used with 16- and 32-bpp bitmaps. This member can be one of the following values.
Value | Meaning
BI_RGB | An uncompressed format.
BI_RLE8 | A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format is a two-byte format consisting of a count byte followed by a byte containing a color index. If bV5Compression is BI_RGB and the bV5BitCount member is 16, 24, or 32, the bitmap array specifies the actual intensities of blue, green, and red rather than using color table indexes. For more information, see Bitmap Compression.
BI_RLE4 | An RLE format for bitmaps with 4 bpp. The compression format is a two-byte format consisting of a count byte followed by two word-length color indexes. For more information, see Bitmap Compression.
BI_BITFIELDS | Specifies that the bitmap is not compressed and that the color table consists of three DWORD color masks that specify the red, green, and blue components of each pixel. Valid when used with 16- and 32-bpp bitmaps.
BI_JPEG | Specifies that the image is compressed using the JPEG file Interchange Format. JPEG compression trades off compression against loss; it can achieve a compression ratio of 20:1 with little noticeable loss.
BI_PNG | Specifies that the image is compressed using the PNG file Interchange Format.

bV5SizeImage
Specifies the size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps.

If bV5Compression is BI_JPEG or BI_PNG, bV5SizeImage is the size of the JPEG or PNG image buffer.

bV5XPelsPerMeter
Specifies the horizontal resolution, in pixels-per-meter, of the target device for the bitmap. An application can use this value to select a bitmap from a resource group that best matches the characteristics of the current device.
bV5YPelsPerMeter
Specifies the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
bV5ClrUsed
Specifies the number of color indexes in the color table that are actually used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the bV5BitCount member for the compression mode specified by bV5Compression.

If bV5ClrUsed is nonzero and bV5BitCount is less than 16, the bV5ClrUsed member specifies the actual number of colors the graphics engine or device driver accesses. If bV5BitCount is 16 or greater, the bV5ClrUsed member specifies the size of the color table used to optimize performance of the system color palettes. If bV5BitCount equals 16 or 32, the optimal color palette starts immediately following the BITMAPV5HEADER. If bV5ClrUsed is nonzero, the color table is used on palettized devices, and bV5ClrUsed specifies the number of entries.

bV5ClrImportant
Specifies the number of color indexes that are required for displaying the bitmap. If this value is zero, all colors are required.
bV5RedMask
Color mask that specifies the red component of each pixel, valid only if bV5Compression is set to BI_BITFIELDS.
bV5GreenMask
Color mask that specifies the green component of each pixel, valid only if bV5Compression is set to BI_BITFIELDS.
bV5BlueMask
Color mask that specifies the blue component of each pixel, valid only if bV5Compression is set to BI_BITFIELDS.
bV5AlphaMask
Color mask that specifies the alpha component of each pixel.
bV5CSType
Specifies the color space of the DIB.

The following table specifies the values for bV5CSType.
Value | Meaning
LCS_CALIBRATED_RGB | This value implies that endpoints and gamma values are given in the appropriate fields.
LCS_sRGB | Specifies that the bitmap is in sRGB color space.
LCS_WINDOWS_COLOR_SPACE | This value indicates that the bitmap is in the system default color space, sRGB.
PROFILE_LINKED | This value indicates that bV5ProfileData points to the file name of the profile to use (gamma and endpoints values are ignored).
PROFILE_EMBEDDED | This value indicates that bV5ProfileData points to a memory buffer that contains the profile to be used (gamma and endpoints values are ignored).

See the LOGCOLORSPACE structure for information that defines a logical color space.

bV5Endpoints
A CIEXYZTRIPLE structure that specifies the x, y, and z coordinates of the three colors that correspond to the red, green, and blue endpoints for the logical color space associated with the bitmap. This member is ignored unless the bV5CSType member specifies LCS_CALIBRATED_RGB.
bV5GammaRed
Toned response curve for red. Used if bV5CSType is set to LCS_CALIBRATED_RGB. Specified in 16^16 format.
bV5GammaGreen
Toned response curve for green. Used if bV5CSType is set to LCS_CALIBRATED_RGB. Specified in 16^16 format.
bV5GammaBlue
Toned response curve for blue. Used if bV5CSType is set to LCS_CALIBRATED_RGB. Specified in 16^16 format.
bV5Intent
Rendering intent for bitmap. This can be one of the following values.
Value | Intent | ICC Name | Meaning
LCS_GM_ABS_COLORIMETRIC | Match | Absolute Colorimetric | Maintains the white point. Matches the colors to their nearest color in the destination gamut.
LCS_GM_BUSINESS | Graphic | Saturation | Maintains saturation. Used for business charts and other situations in which undithered colors are required.
LCS_GM_GRAPHICS | Proof | Relative Colorimetric | Maintains colorimetric match. Used for graphic designs and named colors.
LCS_GM_IMAGES | Picture | Perceptual | Maintains contrast. Used for photographs and natural images.

bV5ProfileData
The offset, in bytes, from the beginning of the BITMAPV5HEADER structure to the start of the profile data. If the profile is embedded, profile data is the actual profile, and it is linked. (The profile data is the null-terminated file name of the profile.) This cannot be a Unicode string. It must be composed exclusively of characters from the Windows character set (code page 1252). These profile members are ignored unless the bV5CSType member specifies PROFILE_LINKED or PROFILE_EMBEDDED.
bV5ProfileSize
Size, in bytes, of embedded profile data.
bV5Reserved
This member has been reserved for future use. Its value should be set to zero.

Remarks

If bV5Height is negative, indicating a top-down DIB, bV5Compression must be either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.

When a DIB is loaded into memory, the profile data (if present) should follow the color table, and the bV5ProfileData should provide the offset of the profile data from the beginning of the BITMAPV5HEADER structure. The value stored in bV5ProfileDate will be different from the value returned by the sizeof operator given the BITMAPV5HEADER argument, because bV5ProfileData is the offset in bytes from the beginning of the BITMAPV5HEADER structure to the start of the profile data. (Bitmap bits do not follow the color table in memory). Applications should modify the bV5ProfileData member after loading the DIB into memory.

For packed DIBs, the profile data should follow the bitmap bits similar to the file format. The bV5ProfileData member should still give the offset of the profile data from the beginning of the BITMAPV5HEADER.

Applications should access the profile data only when bV5Size equals the size of the BITMAPV5HEADER and bV5CSType equals PROFILE_EMBEDDED or PROFILE_LINKED.

If a profile is linked, the path of the profile can be any fully qualified name (including a network path) that can be opened using the CreateFile function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPINFO, BITMAPINFOHEADER, BITMAPV4HEADER, CIEXYZTRIPLE, CreateDIBitmap, LOGCOLORSPACE, StretchDIBits


BLENDFUNCTION

The BLENDFUNCTION structure controls blending by specifying the blending functions for source and destination bitmaps.

typedef struct _BLENDFUNCTION {
  BYTE     BlendOp;
  BYTE     BlendFlags;
  BYTE     SourceConstantAlpha;
  BYTE     AlphaFormat;
}BLENDFUNCTION, *PBLENDFUNCTION, *LPBLENDFUNCTION;

Members

BlendOp
Specifies the source blend operation. Currently, the only source and destination blend operation that has been defined is AC_SRC_OVER. For details, see the following Remarks section.
BlendFlags
Must be zero.
SourceConstantAlpha
Specifies an alpha transparency value to be used on the entire source bitmap. The SourceConstantAlpha value is combined with any per-pixel alpha values in the source bitmap. If you set SourceConstantAlpha to 0, it is assumed that your image is transparent. Set the SourceConstantAlpha value to 255 (opaque) when you only want to use per-pixel alpha values.
AlphaFormat
This member controls the way the source and destination bitmaps are interpreted. AlphaFormat has the following value.
Value | Meaning
AC_SRC_ALPHA | This flag is set when the bitmap has an Alpha channel (that is, per-pixel alpha). Note that the APIs use premultiplied alpha, which means that the red, green and blue channel values in the bitmap must be premultiplied with the alpha channel value. For example, if the alpha channel value is x, the red, green and blue channels must be multiplied by x and divided by 0xff prior to the call.

Remarks

When the AlphaFormat parameter is AC_SRC_ALPHA, the source bitmap must be 32 bpp. If it is not, the AlphaBlend function will fail.

When the BlendOp parameter is AC_SRC_OVER , the source bitmap is placed over the destination bitmap based on the alpha values of the source pixels.

If the source bitmap has no per-pixel alpha value (that is, AC_SRC_ALPHA is not set), the SourceConstantAlpha value determines the blend of the source and destination bitmaps, as shown in the following table. Note that SCA is used for SourceConstantAlpha here. Also, SCA is divided by 255 because it has a value that ranges from 0 to 255.

Dst.Red
= Src.Red * (SCA/255.0)

+ Dst.Red * (1.0 - (SCA/255.0))
Dst.Green
= Src.Green * (SCA/255.0)

+ Dst.Green * (1.0 - (SCA/255.0))
Dst.Blue
= Src.Blue * (SCA/255.0)

+ Dst.Blue * (1.0 - (SCA/255.0))

If the destination bitmap has an alpha channel, then:

Dst.Alpha = Src.Alpha * (SCA/255.0) + Dst.Alpha * (1.0 - (SCA/255.0))

If the source bitmap does not use SourceConstantAlpha (that is, it equals 0xFF), the per-pixel alpha determines the blend of the source and destination bitmaps, as shown in the following table.

Dst.Red

= Src.Red

+ (1 - Src.Alpha) * Dst.Red

Dst.Green

= Src.Green

+ (1 - Src.Alpha) * Dst.Green

Dst.Blue

= Src.Blue

+ (1 - Src.Alpha) * Dst.Blue

If the destination bitmap has an alpha channel, then:

Dest.alpha

= Src.Alpha

+ (1 - SrcAlpha) * Dst.Alpha

If the source has both the SourceConstantAlpha (that is, it is not 0xFF) and per-pixel alpha, the source is pre-multiplied by the SourceConstantAlpha and then the blend is based on the per-pixel alpha. The following tables show this. Note that SourceConstantAlpha is divided by 255 because it has a value that ranges from 0 to 255.

Src.Red

= Src.Red
* SourceConstantAlpha / 255.0;
Src.Green

= Src.Green

* SourceConstantAlpha / 255.0;
Src.Blue

= Src.Blue
* SourceConstantAlpha / 255.0;
Src.Alpha

= Src.Alpha

* SourceConstantAlpha / 255.0;

Dst.Red

= Src.Red
+ (1 - Src.Alpha) * Dst.Red
Dst.Green
= Src.Green

+ (1 - Src.Alpha) * Dst.Green
Dst.Blue
= Src.Blue
+ (1 - Src.Alpha) * Dst.Blue
Dst.Alpha

=  Src.Alpha

+ (1 - Src.Alpha) * Dst.Alpha

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, AlphaBlend


COLORADJUSTMENT

The COLORADJUSTMENT structure defines the color adjustment values used by the StretchBlt and StretchDIBits functions when the stretch mode is HALFTONE. You can set the color adjustment values by calling the SetColorAdjustment function.

typedef struct  tagCOLORADJUSTMENT {
  WORD  caSize;
  WORD  caFlags;
  WORD  caIlluminantIndex;
  WORD  caRedGamma;
  WORD  caGreenGamma;
  WORD  caBlueGamma;
  WORD  caReferenceBlack;
  WORD  caReferenceWhite;
  SHORT caContrast;
  SHORT caBrightness;
  SHORT caColorfulness;
  SHORT caRedGreenTint;
} COLORADJUSTMENT, *PCOLORADJUSTMENT;

Members

caSize
Specifies the size, in bytes, of the structure.
caFlags
Specifies how the output image should be prepared. This member may be set to NULL or any combination of the following values.
Value | Meaning
CA_NEGATIVE | Specifies that the negative of the original image should be displayed.
CA_LOG_FILTER | Specifies that a logarithmic function should be applied to the final density of the output colors. This will increase the color contrast when the luminance is low.

caIlluminantIndex
Specifies the type of standard light source under which the image is viewed. This member may be set to one of the following values.
Value | Meaning
ILLUMINANT_DEVICE_DEFAULT | Device's default. Standard used by output devices.
ILLUMINANT_A | Tungsten lamp.
ILLUMINANT_B | Noon sunlight.
ILLUMINANT_C | NTSC daylight.
ILLUMINANT_D50 | Normal print.
ILLUMINANT_D55 | Bond paper print.
ILLUMINANT_D65 | Standard daylight. Standard for CRTs and pictures.
ILLUMINANT_D75 | Northern daylight.
ILLUMINANT_F2 | Cool white lamp.
ILLUMINANT_TUNGSTEN | Same as ILLUMINANT_A.
ILLUMINANT_DAYLIGHT | Same as ILLUMINANT_C.
ILLUMINANT_FLUORESCENT | Same as ILLUMINANT_F2.
ILLUMINANT_NTSC | Same as ILLUMINANT_C.

caRedGamma
Specifies the nth power gamma-correction value for the red primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma correction.
caGreenGamma
Specifies the nth power gamma-correction value for the green primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma correction.
caBlueGamma
Specifies the nth power gamma-correction value for the blue primary of the source colors. The value must be in the range from 2500 to 65,000. A value of 10,000 means no gamma correction.
caReferenceBlack
Specifies the black reference for the source colors. Any colors that are darker than this are treated as black. The value must be in the range from 0 to 4000.
caReferenceWhite
Specifies the white reference for the source colors. Any colors that are lighter than this are treated as white. The value must be in the range from 6000 to 10,000.
caContrast
Specifies the amount of contrast to be applied to the source object. The value must be in the range from –100 to 100. A value of 0 means no contrast adjustment.
caBrightness
Specifies the amount of brightness to be applied to the source object. The value must be in the range from –100 to 100. A value of 0 means no brightness adjustment.
caColorfulness
Specifies the amount of colorfulness to be applied to the source object. The value must be in the range from –100 to 100. A value of 0 means no colorfulness adjustment.
caRedGreenTint
Specifies the amount of red or green tint adjustment to be applied to the source object. The value must be in the range from –100 to 100. Positive numbers adjust towards red and negative numbers adjust towards green. Zero means no tint adjustment.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, GetColorAdjustment, SetColorAdjustment, SetStretchBltMode, StretchBlt, StretchDIBits


DIBSECTION

The DIBSECTION structure contains information about a DIB created by calling the CreateDIBSection function. A DIBSECTION structure includes information about the bitmap's dimensions, color format, color masks, optional file mapping object, and optional bit values storage offset. An application can obtain a filled-in DIBSECTION structure for a given DIB by calling the GetObject function.

typedef struct tagDIBSECTION {
  BITMAP              dsBm;
  BITMAPINFOHEADER    dsBmih;
  DWORD               dsBitfields[3];
  HANDLE              dshSection;
  DWORD               dsOffset;
} DIBSECTION, *PDIBSECTION;

Members

dsBm
A BITMAP data structure that contains information about the DIB: its type, its dimensions, its color capacities, and a pointer to its bit values.
dsBmih
A BITMAPINFOHEADER structure that contains information about the color format of the DIB.
dsBitfields
Specifies three DWORD color masks for the DIB. This field is only valid when the BitCount member of the BITMAPINFOHEADER structure has a value greater than 8. Each color mask indicates the bits within a DWORD that are used to encode one of the three color channels (red, green, and blue).
dshSection
Contains a handle to the file mapping object that the CreateDIBSection function used to create the DIB. If CreateDIBSection was called with a NULL value for its hSection parameter, causing the system to allocate memory for the bitmap, the dshSection member will be NULL.
dsOffset
Specifies the offset to the bitmap's bit values within the file mapping object referenced by dshSection. If dshSection is NULL, the dsOffset value has no meaning.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAP, BITMAPINFOHEADER, CreateDIBSection, GetDIBColorTable, GetObject


GRADIENT_RECT

The GRADIENT_RECT structure specifies the index of two vertices in the pVertex array in the GradientFill function. These two vertices form the upper-left and lower-right boundaries of a rectangle.

typedef struct _GRADIENT_RECT {
  ULONG    UpperLeft;
  ULONG    LowerRight;
}GRADIENT_RECT, *PGRADIENT_RECT;

Members

UpperLeft
Specifies the upper-left corner of a rectangle.
LowerRight
Specifies the lower-right corner of a rectangle.

Remarks

The GRADIENT_RECT structure contains the values used in the dwMode parameter of the GradientFill function. For related GradientFill structures, see GRADIENT_TRIANGLE and TRIVERTEX.

For an example of the use of this structure, see Drawing a Shaded Rectangle.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, GradientFill, GRADIENT_TRIANGLE, TRIVERTEX


GRADIENT_TRIANGLE

The GRADIENT_TRIANGLE structure specifies the index of three vertices in the pVertex array in the GradientFill function. These three vertices form one triangle.

typedef struct _GRADIENT_TRIANGLE {
  ULONG    Vertex1;
  ULONG    Vertex2;
  ULONG    Vertex3;
}GRADIENT_TRIANGLE, *PGRADIENT_TRIANGLE;

Members

Vertex1
First point of the triangle where sides intersect.
Vertex2
Second point of the triangle where sides intersect.
Vertex3
Third point of the triangle where sides intersect.

Remarks

The GRADIENT_TRIANGLE structure contains the values used in the dwMode parameter of the GradientFill function. For related GradientFill structures, see GRADIENT_RECT and TRIVERTEX.

For an example of this function, see Drawing a Shaded Triangle.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, GradientFill, GRADIENT_RECT, TRIVERTEX


RGBQUAD

The RGBQUAD structure describes a color consisting of relative intensities of red, green, and blue.

typedef struct tagRGBQUAD {
  BYTE    rgbBlue;
  BYTE    rgbGreen;
  BYTE    rgbRed;
  BYTE    rgbReserved;
} RGBQUAD;

Members

rgbBlue
Specifies the intensity of blue in the color.
rgbGreen
Specifies the intensity of green in the color.
rgbRed
Specifies the intensity of red in the color.
rgbReserved
Reserved; must be zero.

Remarks

The bmiColors member of the BITMAPINFO structure consists of an array of RGBQUAD structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPINFO, CreateDIBitmap, CreateDIBSection, GetDIBits, SetDIBits, SetDIBitsToDevice, StretchDIBits


RGBTRIPLE

The RGBTRIPLE structure describes a color consisting of relative intensities of red, green, and blue. The bmciColors member of the BITMAPCOREINFO structure consists of an array of RGBTRIPLE structures.

typedef struct tagRGBTRIPLE {
  BYTE rgbtBlue;
  BYTE rgbtGreen;
  BYTE rgbtRed;
} RGBTRIPLE;

Members

rgbtBlue
Specifies the intensity of blue in the color.
rgbtGreen
Specifies the intensity of green in the color.
rgbtRed
Specifies the intensity of red in the color.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, BITMAPCOREINFO


SIZE

The SIZE structure specifies the width and height of a rectangle.

typedef struct tagSIZE {
  LONG cx;
  LONG cy;
} SIZE, *PSIZE;

Members

cx
Specifies the rectangle's width. The units depend on which function uses this.
cy
Specifies the rectangle's height. The units depend on which function uses this.

Remarks

The rectangle dimensions stored in this structure may correspond to viewport extents, window extents, text extents, bitmap dimensions, or the aspect-ratio filter for some extended functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, GetAspectRatioFilterEx, GetBitmapDimensionEx, GetTextExtentPoint32, GetViewportExtEx, GetWindowExtEx, ScaleViewportExtEx, ScaleWindowExtEx, SetBitmapDimensionEx, SetViewportExtEx, SetWindowExtEx


TRIVERTEX

The TRIVERTEX structure contains color information and position information.

typedef struct _TRIVERTEX {
  LONG        x;
  Long        y;
  COLOR16     Red;
  COLOR16     Green;
  COLOR16     Blue;
  COLOR16     Alpha;
}TRIVERTEX, *PTRIVERTEX;

Members

x
Specifies the x-coordinate, in logical units, of the upper-left corner of the rectangle.
y
Specifies the y-coordinate, in logical units, of the upper-left corner of the rectangle.
Red
Indicates color information at the point of x, y.
Green
Indicates color information at the point of x, y.
Blue
Indicates color information at the point of x, y.
Alpha
Indicates color information at the point of x, y.

Remarks

In the TRIVERTEX structure, x and y indicate position in the same manner as in the POINTL structure contained in the wtypes.h header file. Red, Green, Blue, and Alpha members indicate color information at the point x, y. The color information of each channel is specified as a value from 0x0000 to 0xff00. This allows higher color resolution for an object that has been split into small triangles for display. The TRIVERTEX structure contains information needed by the pVertex parameter of GradientFill.

For an example of the use of this structure, see Drawing a Shaded Triangle and Drawing a Shaded Rectangle.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Structures, GradientFill, POINTL


Bitmap Macros

The following macro is used with bitmaps.

MAKEROP4


MAKEROP4

The MAKEROP4 macro creates a quaternary raster operation code for use with the MaskBlt function. The macro takes two ternary raster operation codes as input, one for the foreground and one for the background, and packs their Boolean operation indexes into the high-order word of a 32-bit value. The low-order word of this value will be ignored.

DWORD MAKEROP4(
  DWORD fore, // foreground ternary raster operation code
  DWORD back  // background ternary raster operation code
);

Parameters

fore
Specifies a foreground ternary raster operation code.
back
Specifies a background ternary raster operation code

Return Values

The return value is a DWORD quaternary raster operation code for use with the MaskBlt function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Bitmaps Overview, Bitmap Macros, MaskBlt


Brushes

A brush is a graphics tool that a Win32®-based application uses to paint the interior of polygons, ellipses, and paths. Drawing applications use brushes to paint shapes; word processing applications use brushes to paint rules; computer-aided design (CAD) applications use brushes to paint the interiors of cross-section views; and spreadsheet applications use brushes to paint the sections of pie charts and the bars in bar graphs.

  • About Brushes
  • Using Brushes
  • Brush Reference


About Brushes

There are two types of brushes: logical and physical. A logical brush is a description of the ideal bitmap that an application uses to paint shapes. A physical brush is the actual bitmap that a device driver creates based on an application's logical-brush definition. For more information about bitmaps, see Bitmaps.

When an application calls one of the functions that creates a brush, it retrieves a handle that identifies a logical brush. When the application passes this handle to the SelectObject function, the device driver for the corresponding display or printer creates the physical brush.

The following topics describe brushes:

  • Brush Origin
  • Logical Brush Types
  • Pattern Block Transfer
  • ICM-Enabled Brush Functions


Brush Origin

When an application calls a drawing function to paint a shape, the system positions a brush at the start of the paint operation and maps a pixel in the brush bitmap to the client area at the window origin, which is the upper-left corner of the window. The coordinates of the pixel that the system maps are called the brush origin. The default brush origin is located in the upper-left corner of the brush bitmap, at the coordinates (0,0). The system then copies the brush across the client area, forming a pattern that is as tall as the bitmap. The copy operation continues, row by row, until the entire client area is filled. However, the brush pattern is visible only within the boundaries of the specified shape.

There are instances when the default brush origin should not be used. For example, it may be necessary for an application to use the same brush to paint the backgrounds of its parent and child windows and blend a child window's background with that of the parent window. To do this, the application should reset the brush origin by calling the SetBrushOrgEx function and shifting the origin the required number of pixels. (An application can retrieve the current brush origin by calling the GetBrushOrgEx function.)

The following illustration shows a five-pointed star filled by using an application-defined brush. The illustration shows a zoomed image of the brush, as well as the location to which it was mapped at the beginning of the paint operation.


Logical Brush Types

There are four types of logical brushes: solid, stock, hatch, and pattern. These brushes are shown in the following illustration.

The stock and hatch types each have several predefined brushes.

The CreateBrushIndirect function creates a logical brush with a specified style, color, and pattern.


Solid Brush

A solid brush is a logical brush that contains 64 pixels of the same color. An application can create a solid logical brush by calling the CreateSolidBrush function, specifying the color of the brush required. After creating the solid brush, the application can select it into its device context and use it to paint filled shapes.


Stock Brush

There are seven predefined logical stock brushes maintained by the graphics device interface (GDI). There are also 21 predefined logical stock brushes maintained by the window management interface (USER).

The following rectangles were painted by using the seven predefined stock brushes.

An application can retrieve a handle identifying one of the seven stock brushes by calling the GetStockObject function, specifying the brush type.

The 21 stock brushes maintained by the window management interface correspond to the colors of window elements such as menus, scroll bars, and buttons. An application can obtain a handle identifying one of these brushes by calling the GetSysColorBrush function and specifying a system-color value. An application can retrieve the color corresponding to a particular window element by calling the GetSysColor function. An application can set the color corresponding to a window element by calling the SetSysColors function.


Hatch Brush

There are six predefined logical hatch brushes maintained by GDI. The following rectangles were painted by using the six predefined hatch brushes.

An application can create a hatch brush by calling the CreateHatchBrush function, specifying one of the six hatch styles.


Pattern Brush

A pattern (or custom) brush is created from an application-defined bitmap or device-independent bitmap (DIB). The following rectangles were painted by using different pattern brushes.

To create a logical pattern brush, an application must first create a bitmap. After creating the bitmap, the application can create the logical pattern brush by calling the CreatePatternBrush or CreateDIBPatternBrushPt function, supplying a handle that identifies the bitmap (or DIB). The brushes that appear in the preceding illustration were created from monochrome bitmaps. For a description of bitmaps, DIBs, and the functions that create them, see Bitmaps.


Pattern Block Transfer

The name of the PatBlt function (an abbreviation for pattern block transfer) implies that this function simply replicates the brush (or pattern) until it fills a specified rectangle. However, the function is actually much more powerful. Before replicating the brush, it combines the color data for the pattern with the color data for the existing pixels on the video display by using a raster operation (ROP). An ROP is a bitwise operation that is applied to the bits of color data for the replicated brush and the bits of color data for the target rectangle on the display device. There are 256 ROPs; however, the PatBlt function recognizes only those that require a pattern and a destination (not those that require a source). The following table identifies the most common ROPs.

ROP | Description
PATCOPY | Copies the pattern to the destination bitmap.
PATINVERT | Combines the destination bitmap with the pattern by using the Boolean XOR operator.
DSTINVERT | Inverts the destination bitmap.
BLACKNESS | Turns all output to binary zeroes.
WHITENESS | Turns all output to binary ones.

For more information, see Raster Operation Codes.


ICM-Enabled Brush Functions

Microsoft® Windows® 98 and Microsoft® Windows® 2000 have been designed to work with Microsoft® Image Color Management (ICM). ICM technology ensures that a color image, graphic, or text object is rendered as close as possible to its original intent on any device, despite differences in imaging technologies and color capabilities between devices. Whether you are scanning an image or other graphic on a color scanner, downloading it over the Internet, viewing or editing it on the screen, or outputting it to paper, film, or other media, ICM 2.0 helps you keep its colors consistent and accurate. For more information on ICM, see About Image Color Management Version 2.0.

The following brush functions are enabled for use with ICM:

  • CreateBrushIndirect
  • CreateDIBPatternBrush
  • CreateDIBPatternBrushPt
  • CreateHatchBrush
  • CreatePatternBrush
  • CreateSolidBrush


Using Brushes

You can use a brush to paint the interior of virtually any shape by using a graphics device interface (GDI) function. This includes the interiors of rectangles, ellipses, polygons, and paths. Depending on the requirements of your application, you can use a solid brush of a specified color, a stock brush, a hatch brush, or a pattern brush.

This section contains code samples that demonstrate the creation of a custom brush dialog box. The dialog box contains a grid that represents the bitmap the system uses as a brush. A user can use this grid to create a pattern-brush bitmap and then view the custom pattern by clicking the Test Pattern button.

The following illustration shows a pattern created by using the Custom Brush dialog box.

To display a dialog box, you must first create a dialog box template. The following dialog box template defines the Custom Brush dialog box.

CustBrush DIALOG 6, 18, 160, 118
STYLE WS_DLGFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "Custom Brush"
FONT 8, "MS Sans Serif"
BEGIN
    CONTROL         "", IDD_GRID, "Static", SS_BLACKFRAME |
                    WS_CHILD, 3, 2, 83, 79
    CONTROL         "", IDD_RECT, "Static", SS_BLACKFRAME |
                    WS_CHILD, 96, 11, 57, 28
    PUSHBUTTON      "Test Pattern", IDD_PAINTRECT, 96, 47, 57, 14
    PUSHBUTTON      "OK", IDD_OK, 29, 98, 40, 14
    PUSHBUTTON      "Cancel", IDD_CANCEL, 92, 98, 40, 14
END

The Custom Brush dialog box contains five controls: a bitmap-grid window, a pattern-viewing window, and three push buttons, labeled Test Pattern, OK, and Cancel. The Test Pattern push button enables the user to view the pattern. The dialog box template specifies the overall dimensions of the dialog box window, assigns a value to each control, specifies the location of each control, and so forth. For more information, see Dialog Boxes.

The control values in the dialog box template are constants that have been defined as follows in the application's header file.

#define IDD_GRID      120
#define IDD_RECT      121
#define IDD_PAINTRECT 122
#define IDD_OK        123
#define IDD_CANCEL    124

After you create a dialog box template and include it in the application's resource-definition file, you must write a dialog procedure. This procedure processes messages that the system sends to the dialog box. The following excerpt from an application's source code shows the dialog box procedure for the Custom Brush dialog box and the two application-defined functions it calls.

BOOL CALLBACK BrushDlgProc( HWND hdlg, UINT message, LONG wParam,
                            LONG lParam)
{
    static HWND hwndGrid;       // grid-window control
    static HWND hwndBrush;      // pattern-brush control
    static RECT rctGrid;        // grid-window rectangle
    static RECT rctBrush;       // pattern-brush rectangle
    static UINT bBrushBits[8];  // bitmap bits
    static RECT rect[64];       // grid-cell array
    static HBITMAP hbm;         // bitmap handle
    HBRUSH hbrush;              // current brush
    HBRUSH hbrushOld;           // default brush
    HRGN hrgnCell;              // test-region handle
    HDC hdc;                    // device context (DC) handle
    int x, y, deltaX, deltaY;   // drawing coordinates
    POINTS ptlHit;              // mouse coordinates
    int i;                      // count variable

    switch (message)
        {
        case WM_INITDIALOG:

            // Retrieve a window handle for the grid-window and
            // pattern-brush controls.

            hwndGrid = GetDlgItem(hdlg, IDD_GRID);
            hwndBrush = GetDlgItem(hdlg, IDD_RECT);

            // Initialize the array of bits that defines the
            // custom brush pattern with the value 1 to produce a
            // solid white brush.

            for (i=0; i<8; i++)
                bBrushBits[i] = 0xFF;

            // Retrieve dimensions for the grid-window and pattern-
            // brush controls.

            GetClientRect(hwndGrid, &rctGrid);
            GetClientRect(hwndBrush, &rctBrush);

            // Determine the width and height of a single cell.

            deltaX = (rctGrid.right - rctGrid.left)/8;
            deltaY = (rctGrid.bottom - rctGrid.top)/8;

            // Initialize the array of cell rectangles.

            for (y=rctGrid.top, i=0; y < rctGrid.bottom; y += deltaY)
            {
                for(x=rctGrid.left; x < (rctGrid.right - 8) && i < 64;
                        x += deltaX, i++)
                {
                    rect[i].left = x; rect[i].top = y;
                    rect[i].right = x + deltaX;
                    rect[i].bottom = y + deltaY;
                }
            }
            return FALSE;

        case WM_PAINT:

            // Draw the grid.

            hdc = GetDC(hwndGrid);

            for (i=rctGrid.left; i<rctGrid.right;
                 i+=(rctGrid.right - rctGrid.left)/8)
            {
                 MoveToEx(hdc, i, rctGrid.top, NULL);
                 LineTo(hdc, i, rctGrid.bottom);
            }
            for (i=rctGrid.top; i<rctGrid.bottom;
                 i+=(rctGrid.bottom - rctGrid.top)/8)
            {
                 MoveToEx(hdc, rctGrid.left, i, NULL);
                 LineTo(hdc, rctGrid.right, i);
            }
            ReleaseDC(hwndGrid, hdc);
            return FALSE;

        case WM_LBUTTONDOWN:

            // Store the mouse coordinates in a POINT structure.

            ptlHit = MAKEPOINTS((POINTS FAR *)lParam);

            // Create a rectangular region with dimensions and
            // coordinates that correspond to those of the grid
            // window.

            hrgnCell = CreateRectRgn(rctGrid.left, rctGrid.top,
                        rctGrid.right, rctGrid.bottom);

            // Retrieve a window DC for the grid window.

            hdc = GetDC(hwndGrid);

            // Select the region into the DC.

            SelectObject(hdc, hrgnCell);

            // Test for a button click in the grid-window rectangle.

            if (PtInRegion(hrgnCell, ptlHit.x, ptlHit.y))
            {
                // A button click occurred in the grid-window
                // rectangle; isolate the cell in which it occurred.

                for(i=0; i<64; i++)
                {
                    DeleteObject(hrgnCell);

                    hrgnCell = CreateRectRgn(rect[i].left,
                               rect[i].top,
                               rect[i].right, rect[i].bottom);

                    if (PtInRegion(hrgnCell, ptlHit.x, ptlHit.y))
                    {
                        InvertRgn(hdc, hrgnCell);

                        // Set the appropriate brush bits.

                         if (i % 8 == 0)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x80;
                         else if (i % 8 == 1)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x40;
                         else if (i % 8 == 2)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x20;
                         else if (i % 8 == 3)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x10;
                         else if (i % 8 == 4)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x08;
                         else if (i % 8 == 5)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x04;
                         else if (i % 8 == 6)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x02;
                         else if (i % 8 == 7)
                            bBrushBits[i/8] = bBrushBits[i/8] ^ 0x01;

                      // Exit the "for" loop after the bit is set.

                         break;
                    } // end if

                } // end for

            } // end if

            // Release the DC for the control.

            ReleaseDC(hwndGrid, hdc);
            return TRUE;

        case WM_COMMAND:
            switch (wParam)
            {
               case IDD_PAINTRECT:

                    hdc = GetDC(hwndBrush);

                    // Create a monochrome bitmap.

                    hbm = CreateBitmap(8, 8, 1, 1,
                          (LPBYTE)bBrushBits);

                    // Select the custom brush into the DC.

                    hbrush = CreatePatternBrush(hbm);

                    hbrushOld = SelectObject(hdc, hbrush);

                    // Use the custom brush to fill the rectangle.

                    Rectangle(hdc, rctBrush.left, rctBrush.top,
                              rctBrush.right, rctBrush.bottom);

                    // Clean up memory.
                    SelectObject(hdc, hbrushOld);
                    DeleteObject(hbrush);
                    DeleteObject(hbm);

                    ReleaseDC(hwndBrush, hdc);
                    return TRUE;

                case IDD_OK:

                case IDD_CANCEL:
                    EndDialog(hdlg, TRUE);
                    return TRUE;

            } // end switch
            break;
        default:
            return FALSE;
        }
}

int GetStrLngth(LPTSTR cArray)
{
    int i = 0;

    while (cArray[i++] != 0);
    return i-1;

}

DWORD RetrieveWidth(LPTSTR cArray, int iLength)
{
    int i, iTmp;
    double dVal, dCount;

    dVal = 0.0;
    dCount = (double)(iLength-1);
    for (i=0; i<iLength; i++)
    {
        iTmp = cArray[i] - 0x30;
        dVal = dVal + (((double)iTmp) * pow(10.0, dCount--));
    }

    return (DWORD)dVal;
}

The dialog box procedure for the Custom Brush dialog box processes four messages, as described in the following table.

Message | Action
WM_INITDIALOG | Retrieves a window handle and dimensions for the grid-window and pattern-brush controls, computes the dimensions of a single cell in the grid-window control, and initializes an array of grid-cell coordinates.
WM_PAINT | Draws the grid pattern in the grid-window control.
WM_LBUTTONDOWN | Determines whether the cursor is within the grid-window control when the user presses the left mouse button. If so, the dialog box procedure inverts the appropriate grid cell and records the state of that cell in an array of bits that is used to create the bitmap for the custom brush.
WM_COMMAND | Processes input for the three push button controls. If the user clicks the Test Pattern button, the dialog box procedure paints the Test Pattern control with the new custom brush pattern. If the user clicks the OK or Cancel button, the dialog box procedure performs actions accordingly.

For more information about messages and message processing, see Messages and Message Queues.

After you write the dialog box procedure, include the function definition for the procedure in the application's header file and then call the dialog box procedure at the appropriate point in the application.

The following excerpt from the application's header file shows the function definition for the dialog box procedure and the two functions it calls.

BOOL CALLBACK BrushDlgProc(HWND, UINT, WPARAM, LPARAM);
int GetStrLngth(LPTSTR);
DWORD RetrieveWidth(LPTSTR, int);

Finally, the following code shows how the dialog box procedure is called from the application's source-code file.

    DialogBox((HANDLE)GetModuleHandle(NULL),
        (LPTSTR)"CustBrush",
        hWnd,
        (DLGPROC) BrushDlgProc);

This call is usually made in response to the user choosing an option from the application's menu.


Brush Reference

The following elements are used with brushes:

  • Brush Functions
  • Brush Structures


Brush Functions

The following functions are used with brushes.

Function | Description
CreateBrushIndirect | Creates a brush with a specified style, color, and pattern
CreateDIBPatternBrushPt | Creates a brush with the pattern from a DIB
CreateHatchBrush | Creates a brush with a hatch pattern and color
CreatePatternBrush | Creates a brush with a bitmap pattern
CreateSolidBrush | Creates a brush with a solid color
GetBrushOrgEx | Gets the brush origin for a device context
GetSysColorBrush | Gets a handle for a brush that corresponds to a color index
PatBlt | Paints a rectangle
SetBrushOrgEx | Sets the brush origin for a device context

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of Windows.

CreateDIBPatternBrush


CreateBrushIndirect

The CreateBrushIndirect function creates a logical brush that has the specified style, color, and pattern.

HBRUSH CreateBrushIndirect(
  CONST LOGBRUSH *lplb   // brush information
);

Parameters

lplb
[in] Pointer to a LOGBRUSH structure that contains information about the brush.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateBrushIndirect, it can select it into any device context by calling the SelectObject function.

A brush created by using a monochrome bitmap (one color plane, one bit per pixel) is drawn using the current text and background colors. Pixels represented by a bit set to 0 are drawn with the current text color; pixels represented by a bit set to 1 are drawn with the current background color.

When you no longer need the brush, call the DeleteObject function to delete it.

ICM: No color is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

Windows 95/98/Me: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.

Windows NT/2000 or later: Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, DeleteObject, GetBrushOrgEx, LOGBRUSH, SelectObject, SetBrushOrgEx


CreateDIBPatternBrush

The CreateDIBPatternBrush function creates a logical brush that has the pattern specified by the specified device-independent bitmap (DIB). The brush can subsequently be selected into any device context that is associated with a device that supports raster operations.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the CreateDIBPatternBrushPt function.

HBRUSH CreateDIBPatternBrush(
  HGLOBAL hglbDIBPacked,  // handle to DIB
  UINT fuColorSpec        // color table data
);

Parameters

hglbDIBPacked
[in] Handle to a global memory object containing a packed DIB, which consists of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of the bitmap.

Windows 95/98/Me: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.

Windows NT/2000 or later: Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

fuColorSpec
[in] Specifies whether the bmiColors member of the BITMAPINFO structure is initialized and, if so, whether this member contains explicit red, green, blue (RGB) values or indexes into a logical palette. The fuColorSpec parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | A color table is provided and consists of an array of 16-bit indexes into the logical palette of the device context into which the brush is to be selected.
DIB_RGB_COLORS | A color table is provided and contains literal RGB values.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When an application selects a two-color DIB pattern brush into a monochrome device context, the system does not acknowledge the colors specified in the DIB; instead, it displays the pattern brush using the current background and foreground colors of the device context. Pixels mapped to the first color of the DIB (offset 0 in the DIB color table) are displayed using the foreground color; pixels mapped to the second color (offset 1 in the color table) are displayed using the background color.

When you no longer need the brush, call the DeleteObject function to delete it.

ICM: No color is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, BITMAPINFO, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, DeleteObject, SetBkColor, SetTextColor


CreateDIBPatternBrushPt

The CreateDIBPatternBrushPt function creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).

HBRUSH CreateDIBPatternBrushPt(
  CONST VOID *lpPackedDIB,  // bitmap bits
  UINT iUsage               // usage
);

Parameters

lpPackedDIB
[in] Pointer to a packed DIB consisting of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of the bitmap.

Windows 95/98/Me: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.

Windows NT/2000 or later: Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

iUsage
[in] Specifies whether the bmiColors member of the BITMAPINFO structure contains a valid color table and, if so, whether the entries in this color table contain explicit red, green, blue (RGB) values or palette indexes. The iUsage parameter must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | A color table is provided and consists of an array of 16-bit indexes into the logical palette of the device context into which the brush is to be selected.
DIB_RGB_COLORS | A color table is provided and contains literal RGB values.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateDIBPatternBrushPt, it can select that brush into any device context by calling the SelectObject function.

When you no longer need the brush, call the DeleteObject function to delete it.

ICM: No color is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, BITMAPINFO, CreateDIBPatternBrush, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, DeleteObject, GetBrushOrgEx, SelectObject, SetBrushOrgEx


CreateHatchBrush

The CreateHatchBrush function creates a logical brush that has the specified hatch pattern and color.

HBRUSH CreateHatchBrush(
  int fnStyle,      // hatch style
  COLORREF clrref   // foreground color
);

Parameters

fnStyle
[in] Specifies the hatch style of the brush. This parameter can be one of the following values.
Value | Meaning
HS_BDIAGONAL | 45-degree upward left-to-right hatch
HS_CROSS | Horizontal and vertical crosshatch
HS_DIAGCROSS | 45-degree crosshatch
HS_FDIAGONAL | 45-degree downward left-to-right hatch
HS_HORIZONTAL | Horizontal hatch
HS_VERTICAL | Vertical hatch

clrref
[in] Specifies the foreground color of the brush that is used for the hatches. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateHatchBrush, it can select that brush into any device context by calling the SelectObject function.

If an application uses a hatch brush to fill the backgrounds of both a parent and a child window with matching color, it may be necessary to set the brush origin before painting the background of the child window. You can do this by having your application call the SetBrushOrgEx function. Your application can retrieve the current brush origin by calling the GetBrushOrgEx function.

When you no longer need the brush, call the DeleteObject function to delete it.

ICM: No color is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreatePatternBrush, CreateSolidBrush, DeleteObject, GetBrushOrgEx, SelectObject, SetBrushOrgEx, COLORREF, RGB


CreatePatternBrush

The CreatePatternBrush function creates a logical brush with the specified bitmap pattern. The bitmap can be a DIB section bitmap, which is created by the CreateDIBSection function.

HBRUSH CreatePatternBrush(
  HBITMAP hbmp   // handle to bitmap
);

Parameters

hbmp
[in] Handle to the bitmap to be used to create the logical brush.

Windows 95/98/Me: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.

Windows NT/2000 or later: Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A pattern brush is a bitmap that the system uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreatePatternBrush, it can select that brush into any device context by calling the SelectObject function.

You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes.

A brush created by using a monochrome (1 bit per pixel) bitmap has the text and background colors of the device context to which it is drawn. Pixels represented by a 0 bit are drawn with the current text color; pixels represented by a 1 bit are drawn with the current background color.

ICM: No color is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

For an example, see Using Brushes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateDIBSection, CreateHatchBrush, DeleteObject, GetBrushOrgEx, LoadBitmap, SelectObject, SetBrushOrgEx


CreateSolidBrush

The CreateSolidBrush function creates a logical brush that has the specified solid color.

HBRUSH CreateSolidBrush(
  COLORREF crColor   // brush color value
);

Parameters

crColor
[in] Specifies the color of the brush. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value identifies a logical brush.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A solid brush is a bitmap that the system uses to paint the interiors of filled shapes.

After an application creates a brush by calling CreateSolidBrush, it can select that brush into any device context by calling the SelectObject function.

To paint with a system color brush, an application should use GetSysColorBrush(nIndex) instead of CreateSolidBrush(GetSysColor(nIndex)), because GetSysColorBrush returns a cached brush instead of allocating a new one.

ICM: No color management is done at brush creation. However, color management is performed when the brush is selected into an ICM-enabled device context.

For an example, see Creating Colored Pens and Brushes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, DeleteObject, GetSysColorBrush, SelectObject, COLORREF, RGB


GetBrushOrgEx

The GetBrushOrgEx function retrieves the current brush origin for the specified device context. This function replaces the GetBrushOrg function.

BOOL GetBrushOrgEx(
  HDC hdc,       // handle to DC
  LPPOINT lppt   // coordinates of origin
);

Parameters

hdc
[in] Handle to the device context.
lppt
[out] Pointer to a POINT structure that receives the brush origin, in device coordinates.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes.

The brush origin is a set of coordinates with values between 0 and 7, specifying the location of one pixel in the bitmap. The default brush origin coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; the value 7 corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of pixels; the value 7 corresponds to the lowermost row. When the system positions the brush at the start of any painting operation, it maps the origin of the brush to the location in the window's client area specified by the brush origin. For example, if the origin is set to (2,3), the system maps the origin of the brush (0,0) to the location (2,3) on the window's client area.

If an application uses a brush to fill the backgrounds of both a parent and a child window with matching colors, it may be necessary to set the brush origin after painting the parent window but before painting the child window.

Windows NT/2000 or later: The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface.

Windows 95/98/Me: Automatic tracking of the brush origin is not supported. Applications must use the UnrealizeObject, SetBrushOrgEx, and SelectObject functions to align the brush before using it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, POINT, SelectObject, SetBrushOrgEx, UnrealizeObject


GetSysColorBrush

The GetSysColorBrush function retrieves a handle identifying a logical brush that corresponds to the specified color index.

HBRUSH GetSysColorBrush(
  int nIndex  // system color index
);

Parameters

nIndex
[in] Specifies a color index. This value corresponds to the color used to paint one of the window elements.

Return Values

The return value identifies a logical brush if the nIndex parameter is supported by the current platform. Otherwise, it returns NULL.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes. An application can retrieve the current system colors by calling the GetSysColor function. An application can set the current system colors by calling the SetSysColors function.

An application must not register a window class for a window using a system brush. To register a window class with a system color, see the documentation of the hbrBackground member of the WNDCLASS or WNDCLASSEX structures.

System color brushes track changes in system colors. In other words, when the user changes a system color, the associated system color brush automatically changes to the new color.

To paint with a system color brush, an application should use GetSysColorBrush(nIndex) instead of CreateSolidBrush(GetSysColor(nIndex)), because GetSysColorBrush returns a cached brush instead of allocating a new one.

System color brushes are owned by the system and must not be destroyed.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Brushes Overview, Brush Functions, CreateSolidBrush, GetSysColor, SetSysColors, WNDCLASS, WNDCLASSEX


PatBlt

The PatBlt function paints the specified rectangle using the brush that is currently selected into the specified device context. The brush color and the surface color or colors are combined by using the specified raster operation.

BOOL PatBlt(
  HDC hdc,      // handle to DC
  int nXLeft,   // x-coord of upper-left rectangle corner
  int nYLeft,   // y-coord of upper-left rectangle corner
  int nWidth,   // width of rectangle
  int nHeight,  // height of rectangle
  DWORD dwRop   // raster operation code
);

Parameters

hdc
[in] Handle to the device context.
nXLeft
[in] Specifies the x-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.
nYLeft
[in] Specifies the y-coordinate, in logical units, of the upper-left corner of the rectangle to be filled.
nWidth
[in] Specifies the width, in logical units, of the rectangle.
nHeight
[in] Specifies the height, in logical units, of the rectangle.
dwRop
[in] Specifies the raster operation code. This code can be one of the following values.
Value | Meaning
PATCOPY | Copies the specified pattern into the destination bitmap.
PATINVERT | Combines the colors of the specified pattern with the colors of the destination rectangle by using the Boolean XOR operator.
DSTINVERT | Inverts the destination rectangle.
BLACKNESS | Fills the destination rectangle using the color associated with index 0 in the physical palette. (This color is black for the default physical palette.)
WHITENESS | Fills the destination rectangle using the color associated with index 1 in the physical palette. (This color is white for the default physical palette.)

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The values of the dwRop parameter for this function are a limited subset of the full 256 ternary raster-operation codes; in particular, an operation code that refers to a source rectangle cannot be used.

Not all devices support the PatBlt function. For more information, see the description of the RC_BITBLT capability in the GetDeviceCaps function.

For an example, see Example of Menu-Item Bitmaps.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, GetDeviceCaps


SetBrushOrgEx

The SetBrushOrgEx function sets the brush origin that GDI assigns to the next brush an application selects into the specified device context.

BOOL SetBrushOrgEx(
  HDC hdc,       // handle to device context
  int nXOrg,     // x-coord of new origin
  int nYOrg,     // y-coord of new origin
  LPPOINT lppt   // points to previous brush origin
);

Parameters

hdc
[in] Handle to the device context.
nXOrg
[in] Specifies the x-coordinate, in device units, of the new brush origin. If this value is greater than the brush width, its value is reduced using the modulus operator (nXOrg mod brush width).
nYOrg
[in] Specifies the y-coordinate, in device units, of the new brush origin. If this value is greater than the brush height, its value is reduced using the modulus operator (nYOrg mod brush height).
lppt
[out] Pointer to a POINT structure that receives the previous brush origin.

This parameter can be NULL if the previous brush origin is not required.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A brush is a bitmap that the system uses to paint the interiors of filled shapes.

The brush origin is a pair of coordinates specifying the location of one pixel in the bitmap. The default brush origin coordinates are (0,0). For horizontal coordinates, the value 0 corresponds to the leftmost column of pixels; the width corresponds to the rightmost column. For vertical coordinates, the value 0 corresponds to the uppermost row of pixels; the height corresponds to the lowermost row.

The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface. The brush origin that is set with this call is relative to the upper-left corner of the client area.

An application should call SetBrushOrgEx after setting the bitmap stretching mode to HALFTONE by using SetStretchBltMode. This must be done to avoid brush misalignment.

Windows NT/2000 or later: The system automatically tracks the origin of all window-managed device contexts and adjusts their brushes as necessary to maintain an alignment of patterns on the surface.

Windows 95/98/Me: Automatic tracking of the brush origin is not supported. Applications must use the UnrealizeObject, SetBrushOrgEx, and SelectObject functions to align the brush before using it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Brushes Overview, Brush Functions, GetBrushOrgEx, POINT, SelectObject, SetStretchBltMode, UnrealizeObject


Brush Structures

The following structures are used with brushes.

LOGBRUSH

LOGBRUSH32


LOGBRUSH

The LOGBRUSH structure defines the style, color, and pattern of a physical brush. It is used by the CreateBrushIndirect and ExtCreatePen functions.

typedef struct tagLOGBRUSH {
  UINT     lbStyle;
  COLORREF lbColor;
  LONG     lbHatch;
} LOGBRUSH, *PLOGBRUSH;

Members

lbStyle
Specifies the brush style. The lbStyle member must be one of the following styles.
Value | Meaning
BS_DIBPATTERN A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. For more information, see discussion in lbHatch.

Windows 95: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.
BS_DIBPATTERN8X8 | Same as BS_DIBPATTERN.
BS_DIBPATTERNPT | A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB. For more information, see discussion in lbHatch.
BS_HATCHED | Hatched brush.
BS_HOLLOW | Hollow brush.
BS_NULL | Same as BS_HOLLOW.
BS_PATTERN | Pattern brush defined by a memory bitmap.
BS_PATTERN8X8 | Same as BS_PATTERN.
BS_SOLID | Solid brush.

lbColor
Specifies the color in which the brush is to be drawn. If lbStyle is the BS_HOLLOW or BS_PATTERN style, lbColor is ignored.

If lbStyle is BS_DIBPATTERN or BS_DIBPATTERNPT, the low-order word of lbColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indexes into the currently realized logical palette. The lbColor member must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The color table consists of an array of 16-bit indexes into the currently realized logical palette.
DIB_RGB_COLORS | The color table contains literal RGB values.

If lbStyle is BS_HATCHED or BS_SOLID, lbColor is a COLORREF color value. To create a COLORREF color value, use the RGB macro.

lbHatch
Specifies a hatch style. The meaning depends on the brush style defined by lbStyle.

If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. To obtain this handle, an application calls the GlobalAlloc function with GMEM_MOVEABLE (or LocalAlloc with LMEM_MOVEABLE) to allocate a block of memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB. The pointer derives from the memory block created by LocalAlloc with LMEM_FIXED set or by GlobalAlloc with GMEM_FIXED set, or it is the pointer returned by a call like LocalLock (handle_to_the_dib). A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If lbStyle is BS_HATCHED, the lbHatch member specifies the orientation of the lines used to create the hatch. It can be one of the following values.
Value | Meaning
HS_BDIAGONAL | A 45-degree upward, left-to-right hatch
HS_CROSS | Horizontal and vertical cross-hatch
HS_DIAGCROSS | 45-degree crosshatch
HS_FDIAGONAL | A 45-degree downward, left-to-right hatch
HS_HORIZONTAL | Horizontal hatch
HS_VERTICAL | Vertical hatch

If lbStyle is BS_PATTERN, lbHatch is a handle to the bitmap that defines the pattern. The bitmap cannot be a DIB section bitmap, which is created by the CreateDIBSection function.

If lbStyle is BS_SOLID or BS_HOLLOW, lbHatch is ignored.

Remarks

Although lbColor controls the foreground color of a hatch brush, the SetBkMode and SetBkColor functions control the background color.

Windows 95: Creating brushes from bitmaps or DIBs larger than 8 by 8 pixels is not supported. If a larger bitmap is specified, only a portion of the bitmap is used.

Windows NT/2000 and Windows 98/Me: Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Brushes Overview, Brush Structures, BITMAPINFO, CreateBrushIndirect, CreateDIBSection, ExtCreatePen, LOGBRUSH32, SetBkColor, SetBkMode, COLORREF, RGB


LOGBRUSH32

The LOGBRUSH32 structure defines the style, color, and pattern of a physical brush. It is similar to LOGBRUSH, but it is used to maintain compatibility between 32-bit platforms and 64-bit platforms when we record the metafile record on one platform and then play it on another. Thus, it is only used in EMRCREATEBRUSHINDIRECT. If the code will only be on one platform, LOGBRUSH is sufficient.

typedef struct tagLOGBRUSH32 {
  UINT     lbStyle;
  COLORREF lbColor;
  ULONG    lbHatch;
} LOGBRUSH32, *PLOGBRUSH32, NEAR *NPLOGBRUSH32, FAR *LPLOGBRUSH32;

Members

lbStyle
Specifies the brush style. The lbStyle member must be one of the following styles.
Value | Meaning
BS_DIBPATTERN | A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. For more information, see discussion in lbHatch.
BS_DIBPATTERN8X8 | Same as BS_DIBPATTERN.
BS_DIBPATTERNPT | A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB. For more information, see discussion in lbHatch.
BS_HATCHED | Hatched brush.
BS_HOLLOW | Hollow brush.
BS_NULL | Same as BS_HOLLOW.
BS_PATTERN | Pattern brush defined by a memory bitmap.
BS_PATTERN8X8 | Same as BS_PATTERN.
BS_SOLID | Solid brush.

lbColor
Specifies the color in which the brush is to be drawn. If lbStyle is the BS_HOLLOW or BS_PATTERN style, lbColor is ignored.

If lbStyle is BS_DIBPATTERN or BS_DIBPATTERNPT, the low-order word of lbColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indexes into the currently realized logical palette. The lbColor member must be one of the following values.
Value | Meaning
DIB_PAL_COLORS | The color table consists of an array of 16-bit indexes into the currently realized logical palette.
DIB_RGB_COLORS | The color table contains literal RGB values.

If lbStyle is BS_HATCHED or BS_SOLID, lbColor is a COLORREF color value. To create a COLORREF color value, use the RGB macro.

lbHatch
Specifies a hatch style. The meaning depends on the brush style defined by lbStyle.

If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. To obtain this handle, an application calls the GlobalAlloc function with GMEM_MOVEABLE (or LocalAlloc with LMEM_MOVEABLE) to allocate a block of memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB. The pointer derives from the memory block created by LocalAlloc with LMEM_FIXED set or by GlobalAlloc with GMEM_FIXED set, or it is the pointer returned by a call like LocalLock (handle_to_the_dib). A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If lbStyle is BS_HATCHED, the lbHatch member specifies the orientation of the lines used to create the hatch. It can be one of the following values.
Value | Meaning
HS_BDIAGONAL | A 45-degree upward, left-to-right hatch
HS_CROSS | Horizontal and vertical cross-hatch
HS_DIAGCROSS | 45-degree crosshatch
HS_FDIAGONAL | A 45-degree downward, left-to-right hatch
HS_HORIZONTAL | Horizontal hatch
HS_VERTICAL | Vertical hatch

If lbStyle is BS_PATTERN, lbHatch is a handle to the bitmap that defines the pattern. The bitmap cannot be a DIB section bitmap, which is created by the CreateDIBSection function.

If lbStyle is BS_SOLID or BS_HOLLOW, lbHatch is ignored.

Remarks

Although lbColor controls the foreground color of a hatch brush, the SetBkMode and SetBkColor functions control the background color.

Brushes can be created from bitmaps or DIBs larger than 8 by 8 pixels.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Brushes Overview, Brush Structures, BITMAPINFO, CreateDIBSection, EMRCREATEBRUSHINDIRECT, LOGBRUSH, SetBkColor, SetBkMode, COLORREF, RGB


Clipping

Clipping is the process of limiting output to a region or path within the client area of an application window. The following sections discuss clipping.

  • About Clipping
  • Using Clipping
  • Clipping Reference


About Clipping

Clipping is used by Win32®-based applications in a variety of ways. Word processing and spreadsheet applications clip keyboard input to keep it from appearing in the margins of a page or spreadsheet. Computer-aided design (CAD) and drawing applications clip graphics output to keep it from overwriting the edges of a drawing or picture.

A clipping region is a region with edges that are either straight lines or curves. A clip path is a region with edges that are straight lines, Bézier curves, or combinations of both. For more information about regions, see Regions. For more information about paths, see Paths.

This overview covers the following topics:

  • Clipping Regions
  • Clip Paths


Clipping Regions

A clipping region is one of the graphic objects that an application can select into a device context (DC). It is typically rectangular. Some device contexts provide a predefined or default clipping region while others do not. For example, if you obtain a device context handle from the BeginPaint function, the DC contains a predefined rectangular clipping region that corresponds to the invalid rectangle that requires repainting. However, when you obtain a device context handle by calling the GetDC function with a NULL hWnd parameter, or by calling the CreateDC function, the DC does not contain a default clipping region. For more information about device contexts returned by the BeginPaint function, see Painting and Drawing. For more information about device contexts returned by the CreateDC and GetDC functions, see Device Contexts.

Applications can perform a variety of operations on clipping regions. Some of these operations require a handle identifying the region and some do not. For example, an application can perform the following operations directly on a device context's clipping region.

  • Determine whether graphics output appears within the region's borders by passing coordinates of the corresponding line, arc, bitmap, text, or filled shape to the PtVisible function.
  • Determine whether part of the client area intersects a region by calling the RectVisible function.
  • Move the existing region by a specified offset by calling the OffsetClipRgn function.
  • Exclude a rectangular part of the client area from the current clipping region by calling the ExcludeClipRect function.
  • Combine a rectangular part of the client area with the current clipping region by calling the IntersectClipRect function.

After obtaining a handle identifying the clipping region, an application can perform any operation that is common with regions, such as:

  • Combining a copy of the current clipping region with a second region by calling the CombineRgn function.
  • Compare a copy of the current clipping region to a second region by calling the EqualRgn function.
  • Determine whether a point lies within the interior of a copy of the current clipping region by calling the PtInRegion function.


Clip Paths

Like a clipping region, a clip path is another graphics object that an application can select into a device context. Unlike a clipping region, a clip path is always created by an application and it is used for clipping to one or more irregular shapes. For example, an application can use the lines and curves that form the outlines of characters in a string of text to define a clip path.

To create a clip path, it's first necessary to create a path that describes the required irregular shape. Paths are created by calling the appropriate graphics device interface (GDI) drawing functions after calling the BeginPath function and before calling the EndPath function. This collection of functions is called a path bracket. For more information about paths and path brackets, see Paths.

After the path is created, it can be converted to a clip path by calling the SelectClipPath function, identifying a device context, and specifying a usage mode. The usage mode determines how the system combines the new clip path with the device context's original clipping region. The following table describes the usage modes.

Mode | Description
RGN_AND | The clip path includes the intersection (overlapping areas) of the device context's clipping region and the current path.
RGN_COPY | The clip path is the current path.
RGN_DIFF | The clip path includes the device context's clipping region with any intersecting parts of the current path excluded.
RGN_OR | The clip path includes the union (combined areas) of the device context's clipping region and the current path.
RGN_XOR | The clip path includes the union of the device context's clipping region and the current path but excludes the intersection.


Using Clipping

This section contains example code that shows how to generate a clip path consisting of a character string. The example creates a logical font and uses it to draw a string within a clip path, then fills the path by drawing horizontal and vertical lines.

// DoClipPat - Draws a clip path using the specified string
// Return value - TRUE if successful; FALSE otherwise
// lplf - address of a LOGFONT structure that defines the font to
//        use to draw the clip path
// lpsz - address of a string to use for the clip path

BOOL DoClipPath(LPLOGFONT lplf, LPSTR lpsz)
{
    LOGFONT lf;           // logical font structure
    HFONT hfont;          // new logical font handle
    HFONT hfontOld;       // original logical font handle
    HDC hdc;              // display DC handle
    int nXStart, nYStart; // drawing coordinates
    RECT rc;              // rectangle structure for painting window
    SIZE sz;              // size structure that receives text extents
    int nStrLen;          // length of the string
    int i;                // loop counter

    // Retrieve a cached DC for the window.

    hdc = GetDC(hwnd);

    // Erase the current window contents.

    GetClientRect(hwnd, &rc);
    FillRect(hdc, &rc, GetStockObject(WHITE_BRUSH));

    // Use the specified font to create a logical font and select it
    // into the DC.

    hfont = CreateFontIndirect(lplf);
    if (hfont == NULL)
        return FALSE;
    hfontOld = SelectObject(hdc, hfont);

    // Create a clip path.

    nStrLen = lstrlen(lpsz);
    BeginPath(hdc);
        TextOut(hdc, nXStart, nYStart, lpsz, nStrLen);
    EndPath(hdc);
    SelectClipPath(hdc, RGN_DIFF);

    // Retrieve the dimensions of the rectangle surrounding
    // the text.

    GetTextExtentPoint32(hdc, lpsz, nStrLen, &sz);

    // Draw horizontal lines through the clip path.

    for (i = nYStart + 1; i < (nYStart + sz.cy); i += 3)
    {
       MoveToEx(hdc, nXStart, i, (LPPOINT) NULL);
       LineTo(hdc, (nXStart + sz.cx), i);
    }

    // Draw vertical lines through the clip path.

    for (i = nXStart + 1; i < (nXStart + sz.cx); i += 3)
    {
       MoveToEx(hdc, i, nYStart, (LPPOINT) NULL);
       LineTo(hdc, i, (nYStart + sz.cy));
    }

    // Select the original font into the DC and release the DC.

    SelectObject(hdc, hfontOld);
    DeleteObject(hfont);
    ReleaseDC(hwnd, hdc);

    return TRUE;
}

For an example that demonstrates how an application creates a rectangular clipping region, see Regions.


Clipping Reference

The following elements are used with clipping.

  • Clipping Functions


Clipping Functions

The following functions are used with clipping.

Function | Description
ExcludeClipRect | Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.
ExtSelectClipRgn | Combines the specified region with the current clipping region using the specified mode.
GetClipBox | Retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device.
GetClipRgn | Retrieves a handle identifying the current application-defined clipping region for the specified device context.
GetMetaRgn | Retrieves the current metaregion for the specified device context.
GetRandomRgn | Copies the system clipping region of a specified device context to a specific region.
IntersectClipRect | Creates a new clipping region from the intersection of the current clipping region and the specified rectangle.
OffsetClipRgn | Moves the clipping region of a device context by the specified offsets.
PtVisible | Determines whether the specified point is within the clipping region of a device context.
RectVisible | Determines whether any part of the specified rectangle lies within the clipping region of a device context.
SelectClipPath | Selects the current path as a clipping region for a device context, combining the new region with any existing clipping region by using the specified mode.
SelectClipRgn | Selects a region as the current clipping region for the specified device context.
SetMetaRgn | Intersects the current clipping region for the specified device context with the current metaregion and saves the combined region as the new metaregion for the specified device context.


ExcludeClipRect

The ExcludeClipRect function creates a new clipping region that consists of the existing clipping region minus the specified rectangle.

int ExcludeClipRect(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner
  int nTopRect,    // y-coord of upper-left corner
  int nRightRect,  // x-coord of lower-right corner
  int nBottomRect  // y-coord of lower-right corner
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the logical x-coordinate of the upper-left corner of the rectangle.
nTopRect
[in] Specifies the logical y-coordinate of the upper-left corner of the rectangle.
nRightRect
[in] Specifies the logical x-coordinate of the lower-right corner of the rectangle.
nBottomRect
[in] Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Values

The return value specifies the new clipping region's complexity; it can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | No region was created.

Remarks

The lower and right edges of the specified rectangle are not excluded from the clipping region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, IntersectClipRect


ExtSelectClipRgn

The ExtSelectClipRgn function combines the specified region with the current clipping region using the specified mode.

int ExtSelectClipRgn(
  HDC hdc,          // handle to DC
  HRGN hrgn,        // handle to region
  int fnMode        // region-selection mode
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region to be selected. This handle can only be NULL when the RGN_COPY mode is specified.
fnMode
[in] Specifies the operation to be performed. It must be one of the following values.
Value | Meaning
RGN_AND | The new clipping region combines the overlapping areas of the current clipping region and the region identified by hrgn.
RGN_COPY | The new clipping region is a copy of the region identified by hrgn. This is identical to SelectClipRgn. If the region identified by hrgn is NULL, the new clipping region is the default clipping region (the default clipping region is 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 hrgn.
RGN_OR | The new clipping region combines the current clipping region and the region identified by hrgn.
RGN_XOR | The new clipping region combines the current clipping region and the region identified by hrgn but excludes any overlapping areas.

Return Values

The return value specifies the new clipping region's complexity; it can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred.

Remarks

If an error occurs when this function is called, the previous clipping region for the specified device context is not affected.

The ExtSelectClipRgn function assumes that the coordinates for the specified region are specified in device units.

Only a copy of the region identified by the hrgn parameter is used. The region itself can be reused after this call or it can be deleted.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, SelectClipRgn


GetClipBox

The GetClipBox function retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device. The visible area is defined by the current clipping region or clip path, as well as any overlapping windows.

int GetClipBox(
  HDC hdc,      // handle to DC
  LPRECT lprc   // rectangle
);

Parameters

hdc
[in] Handle to the device context.
lprc
[out] Pointer to a RECT structure that is to receive the rectangle dimensions.

Return Values

If the function succeeds, the return value specifies the clipping box's complexity and can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred.

GetClipBox returns logical coordinates based on the given device context.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, RECT


GetClipRgn

The GetClipRgn function retrieves a handle identifying the current application-defined clipping region for the specified device context.

int GetClipRgn(
  HDC hdc,           // handle to DC
  HRGN hrgn          // handle to region
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to an existing region before the function is called. After the function returns, this parameter is a handle to a copy of the current clipping region.

Return Values

If the function succeeds and there is no clipping region for the given device context, the return value is zero. If the function succeeds and there is a clipping region for the given device context, the return value is 1. If an error occurs, the return value is –1.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application-defined clipping region is a clipping region identified by the SelectClipRgn function. It is not a clipping region created when the application calls the BeginPaint function.

If the function succeeds, the hrgn parameter is a handle to a copy of the current clipping region. Subsequent changes to this copy will not affect the current clipping region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, BeginPaint, SelectClipRgn


GetMetaRgn

The GetMetaRgn function retrieves the current metaregion for the specified device context.

int GetMetaRgn(
  HDC hdc,    // handle to DC
  HRGN hrgn   // handle to region
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to an existing region before the function is called. After the function returns, this parameter is a handle to a copy of the current metaregion.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If the function succeeds, hrgn is a handle to a copy of the current metaregion. Subsequent changes to this copy will not affect the current metaregion.

The current clipping region of a device context is defined by the intersection of its clipping region and its metaregion.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, SetMetaRgn


GetRandomRgn

The GetRandomRgn function copies the system clipping region of a specified device context to a specific region.

int GetRandomRgn(
  HDC  hdc,    // handle to DC
  HRGN hrgn,   // handle to region
  INT  iNum    // must be SYSRGN
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to a region. Before the function is called, this identifies an existing region. After the function returns, this identifies a copy of the current system region. The old region identified by hrgn is overwritten.
iNum
[in] This parameter must be SYSRGN.

Return Values

If the function succeeds, the return value is 1. If the function fails, the return value is –1. If the region to be retrieved is NULL, the return value is 0.

Remarks

When using the SYSRGN flag, note that the system clipping region might not be current because of window movements. Nonetheless, it is safe to retrieve and use the system clipping region within the BeginPaint/EndPaint bracket during WM_PAINT processing. In this case, the system region is the intersection of the update region and the current visible area of the window. Any window movement following the return of GetRandomRgn and before EndPaint will result in a new WM_PAINT message. Any other use of the SYSRGN flag may result in painting errors in your application.

In Windows NT/2000, the region returned is in screen coordinates. In Windows 95/98, the region returned is in window coordinates.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, BeginPaint, EndPaint, ExtSelectClipRgn, GetClipRgn, GetClipBox, GetRegionData, OffsetRgn


IntersectClipRect

The IntersectClipRect function creates a new clipping region from the intersection of the current clipping region and the specified rectangle.

int IntersectClipRect(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner
  int nTopRect,    // y-coord of upper-left corner
  int nRightRect,  // x-coord of lower-right corner
  int nBottomRect  // y-coord of lower-right corner
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the logical x-coordinate of the upper-left corner of the rectangle.
nTopRect
[in] Specifies the logical y-coordinate of the upper-left corner of the rectangle.
nRightRect
[in] Specifies the logical x-coordinate of the lower-right corner of the rectangle.
nBottomRect
[in] Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Values

The return value specifies the new clipping region's type and can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred. (The current clipping region is unaffected.)

Remarks

The lower and right-most edges of the given rectangle are excluded from the clipping region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, ExcludeClipRect


OffsetClipRgn

The OffsetClipRgn function moves the clipping region of a device context by the specified offsets.

int OffsetClipRgn(
  HDC hdc,       // handle to DC
  int nXOffset,  // offset along x-axis
  int nYOffset   // offset along y-axis
);

Parameters

hdc
[in] Handle to the device context.
nXOffset
[in] Specifies the number of logical units to move left or right.
nYOffset
[in] Specifies the number of logical units to move up or down.

Return Values

The return value specifies the new region's complexity and can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred. (The current clipping region is unaffected.)

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, SelectClipRgn


PtVisible

The PtVisible function determines whether the specified point is within the clipping region of a device context.

BOOL PtVisible(
  HDC hdc,  // handle to DC
  int X,    // x-coordinate of point
  int Y     // y-coordinate of point
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the logical x-coordinate of the point.
Y
[in] Specifies the logical y-coordinate of the point.

Return Values

If the specified point is within the clipping region of the device context, the return value is nonzero.

If the specified point is not within the clipping region of the device context, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, RectVisible


RectVisible

The RectVisible function determines whether any part of the specified rectangle lies within the clipping region of a device context.

BOOL RectVisible(
  HDC hdc,           // handle to DC
  CONST RECT* lprc   // rectangle
);

Parameters

hdc
[in] Handle to the device context.
lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the specified rectangle.

Return Values

If some portion of the specified rectangle lies within the clipping region, the return value is nonzero.

If no portion of the specified rectangle lies within the clipping region, the return value is zero.

For an example, see Redrawing in the Update Region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, CreateRectRgn, PtVisible, RECT, SelectClipRgn


SelectClipPath

The SelectClipPath function selects the current path as a clipping region for a device context, combining the new region with any existing clipping region using the specified mode.

BOOL SelectClipPath(
  HDC hdc,    // handle to DC
  int iMode   // clipping mode
);

Parameters

hdc
[in] Handle to the device context of the path.
iMode
[in] Specifies the way to use the path. This parameter can be one of the following values.
Value | Meaning
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 with those of the current path 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 Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

For an example, see Using Clipping.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, BeginPath, EndPath


SelectClipRgn

The SelectClipRgn function selects a region as the current clipping region for the specified device context.

int SelectClipRgn(
  HDC hdc,    // handle to DC
  HRGN hrgn   // handle to region
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region to be selected.

Return Values

The return value specifies the region's complexity and can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred. (The previous clipping region is unaffected.)

Windows NT/Windows 2000 or later: To get extended error Information, call GetLastError.

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 SelectClipRgn function assumes that the coordinates for a region are specified in device units.

To remove a device-context's clipping region, specify a NULL region handle.

For an example, see Clipping Output.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, ExtSelectClipRgn


SetMetaRgn

The SetMetaRgn function intersects the current clipping region for the specified device context with the current metaregion and saves the combined region as the new metaregion for the specified device context. The clipping region is reset to a null region.

int SetMetaRgn(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

The return value specifies the new clipping region's complexity and can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred. (The previous clipping region is unaffected.)

Remarks

The current clipping region of a device context is defined by the intersection of its clipping region and its metaregion.

The SetMetaRgn function should only be called after an application's original device context was saved by calling the SaveDC function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Clipping Overview, Clipping Functions, GetMetaRgn, SaveDC


Colors

Color is an important element in the pictures and images generated by Win32®-based applications. This overview describes how Win32-based applications can manage and use colors with pens, brushes, text, or bitmaps.

  • About Colors
  • Using Color
  • Color Reference


About Colors

Color can be used to communicate ideas, show relationships between items, and improve the appeal and quality of output. The Win32 API enables applications to discover the color capabilities of given devices and to choose from the available colors those that best suit their needs.

This overview provides information on the following topics:

• Color Basics

• Color Palettes

Although not described in this overview, image color matching is an important feature of color management that helps ensure that color images look the same whether displayed on screen or printed on paper. For more information, see About Image Color Management Version 2.0.


Color Basics

The color capabilities of devices, such as displays and printers, can range from monochrome to thousands of colors. Because an application may need to generate output for devices throughout this range, it should be prepared to handle varying color capabilities.

An application can discover the number of colors available for a given device by using the GetDeviceCaps function to retrieve the NUMCOLORS value. This value specifies the count of colors available for use by the application. Usually, this count corresponds to a physical property of the output device, such as the number of inks in the printer or the number of distinct color signals the display adapter can transmit to the monitor.

Although the NUMCOLORS value specifies the count of colors, it does not identify what the available colors are. An application can discover what colors are available by enumerating all pens having the PS_SOLID type. Because the device driver that supports a given device usually has a full range of solid pens and because the system requires that solid pens have only colors that the device can generate, enumerating these pens is often equivalent to enumerating the colors. An application can enumerate the pens by using the EnumObjects function. For a code sample showing how, see the section Enumerating Colors.

For more information, see the following topics:

• Color Values

• Color Approximations and Dithering

• Color in Bitmaps

• Color Mixing


Color Values

Color is defined as a combination of three primary colors — red, green, and blue. the system identifies a color by giving it a color value (sometimes called an RGB triplet), which consists of three 8-bit values specifying the intensities of its color components. Black has the minimum intensity for red, green, and blue, so the color value for black is (0, 0, 0). White has the maximum intensity for red, green, and blue, so its color value is (255, 255, 255).

Note If image color matching is enabled, the definition of color and the meaning of a color value depends on the type of color space that is currently set for the device context.

The system and applications use parameters and variables having the COLORREF type to pass and store color values. For example, the EnumObjects function identifies the color of each pen by setting the lopnColor member in a LOGPEN structure to a color value. Applications can extract the individual values of the red, green, and blue components from a color value by using the GetRValue, GetGValue, and GetBValue macros, respectively. Applications can create a color value from individual component values by using the RGB macro. When creating or examining a logical palette, an application uses the RGBQUAD structure to define color values and to examine individual component values.


Color Approximations and Dithering

Although an application can use color without regard to the color capabilities of the device, the resulting output may not be as informative and pleasing as output for which color is carefully chosen. Few, if any, devices guarantee an exact match for every possible color value; therefore, if an application requests a color that the device cannot generate, the system approximates that color by using a color that the device can generate. For example, if an application attempts to create a red pen for a black and white printer, it will receive a black pen instead — the system uses black as the approximation for red.

An application can discover whether the system will approximate a given color by using the GetNearestColor function. The function takes a color value and returns the color value of the closest matching color the device can generate. The method the system uses to determine this approximation depends on the device driver and its color capabilities. In most cases, the approximated color's overall intensity is closest to that of the requested color.

When an application creates a pen or sets the color for text, the system always approximates a color if no exact match exists. When an application creates a solid brush, the system may attempt to simulate the requested color by dithering. Dithering simulates a color by alternating two or more colors in a pattern. For example, different shades of pink can be simulated by alternating different combinations of red and white. Depending on the colors and the pattern, dithering can produce reasonable simulations. It is most useful for monochrome devices, because it expands the number of available "colors" well beyond simple black and white.

The method used to create dithered colors depends on the device driver. Most device drivers use a standard dithering algorithm, which generates a pattern based on the intensity values of the requested red, green, and blue colors. In general, any requested color that cannot be generated by the device is subject to simulation, but an application is not notified when the system simulates a color. Furthermore, an application cannot modify or change the dithering algorithm of the device driver. An application, however, can bypass the algorithm by creating and using pattern brushes. In this way, the application creates its own dithered colors by combining solid colors in the bitmap that it uses to create the brush.


Color in Bitmaps

The system handles colors in bitmaps differently than colors in pens, brushes, and text. Compatible bitmaps, created by using the CreateBitmap or CreateCompatibleBitmap function, are device specific and retain color information in a device-dependent format. No color values are used, and the colors are not subject to approximations and dithering.

Device-independent bitmaps (DIBs) retain color information either as color values or color palette indexes. If color values are used, the colors are subject to approximation, but not dithering. Color palette indexes can only be used with devices that support color palettes. Although the system does not approximate or dither colors identified by indexes, the resulting color may be different than that intended, because the indexes yield valid results only in the context of the color palette that was current at the time the bitmap was created. If the palette changes, so do the colors in the bitmap.


Color Mixing

Color mixing lets an application create new colors by combining the pen or brush color with colors in the existing image. The application can choose either to draw the pen or brush color as is (effectively drawing over any existing image) or to mix the color with the colors already present.

The foreground mix mode, sometimes called the binary raster operation, determines how these colors are mixed. An application can merge colors, preserving all components of both colors; mask colors, removing or moderating components that are not common; or exclusively mask colors, removing or moderating components that are common. There are several variations on these basic mixing operations.

Color mixing is subject to color approximation. If the result of color mixing is a color that the device cannot generate, the system approximates the result, using a color it can generate. If an application mixes dithered colors, the individual colors used to create the dithered color are mixed, and the results are subject to color approximation.

An application sets the foreground mix mode by using the SetROP2 function and retrieves the current mode by using the GetROP2 function.

Although there is a background mix mode, that mode does not control the mixing of colors. Instead, it specifies whether a background color is used when drawing styled lines, hatched brushes, and text.


Color Palettes

A color palette is an array that contains color values identifying the colors that can currently be displayed or drawn on the output device. Color palettes are used by devices that are capable of generating many colors but that can only display or draw a subset of these at any given time. For such devices, the system maintains a system palette to track and manage the current colors of the device. Applications do not have direct access to the system palette. Instead, the system associates a default palette with each device context. Applications can use the colors in the default palette or define their own colors by creating logical palettes and associating them with individual device contexts.

An application can determine whether a device supports color palettes by checking for the RC_PALETTE bit in the RASTERCAPS value returned by the GetDeviceCaps function.


Default Palette

The default palette is an array of color values identifying the colors that can be used with a device context by default. the system associates the default palette with a context whenever an application creates a context for a device that supports color palettes. The default palette ensures that colors are available for use by an application without any further action.

The default palette typically has 20 entries (colors), but the exact number of entries may vary from device to device. This number is equal to the NUMCOLORS value returned by the GetDeviceCaps function. An application can retrieve the color values for colors in the default palette by enumerating solid pens, the same technique used to discover the colors available on nonpalette devices. The colors in the default palette depend on the device. Display devices, for example, often use the 16 standard colors of the VGA display and 4 other colors defined by the Win32 API. Print devices may use other default colors.

When using the default palette, applications use color values to specify pen and text colors. If the requested color is not in the palette, The system approximates the color by using the closest color in the palette. If an application requests a solid brush color that is not in the palette, the system simulates the color by dithering with colors that are in the palette.

To avoid approximations and dithering, applications can also specify pen, brush, and text colors by using color palette indexes rather than color values. A color palette index is an integer value that identifies a specific palette entry. Applications can use color palette indexes in place of color values but must use the PALETTEINDEX macro to create the indexes.

Color palette indexes are only useful for devices that support color palettes. To avoid this device dependence, applications that use the same code to draw to both palette and nonpalette devices should use palette-relative color values to specify pen, brush, and text colors. These values are identical to color values except when creating solid brushes. (On palette devices, a solid brush color specified by a palette-relative color value is subject to color approximation instead of dithering.) Applications must use the PALETTERGB macro to create palette-relative color values.

The system does not allow an application to change the entries in the default palette. To use colors other than those in the default palette, an application must create its own logical palette and select the palette into the device context.


Logical Palette

A logical palette is a color palette that an application creates and associates with a given device context. Logical palettes let applications define and use colors that meet their specific needs. Applications can create any number of logical palettes, using them for separate device contexts or switching between them for a single device context. The maximum number of palettes that an application can create depends on the resources of the system.

An application creates a logical palette by using the CreatePalette function. The application fills a LOGPALETTE structure, which specifies the number of entries and the color values for each entry, and then the application passes the structure to CreatePalette. The function returns a palette handle that the application uses in all subsequent operations to identify the palette. To use colors in the logical palette, the application selects the palette into a device context by using the SelectPalette function and then realizes the palette by using the RealizePalette function. The colors in the palette are available as soon as the logical palette is realized.

An application should limit the size of its logical palettes to just enough entries to represent the colors needed. Applications cannot create logical palettes larger than the maximum palette size, a device-dependent value. Applications can obtain the maximum size by using the GetDeviceCaps function to retrieve the SIZEPALETTE value.

Although an application can specify any color value for a given entry in a logical palette, not all colors can be generated by the given device. The system does not provide a way to discover which colors are supported, but the application can discover the total number of these colors by retrieving the color resolution of the device. The color resolution, specified in color bits per pixel, is equal to the COLORRES value returned by the GetDeviceCaps function. A device that has a color resolution of 18 has 262,144 possible colors. If an application requests a color that is not supported, the system chooses an appropriate approximation.

Once a logical palette is created, an application can change colors in the palette by using the SetPaletteEntries function. If the logical palette has been selected and realized, changing the palette does not immediately affect the colors being displayed. The application must use the UnrealizeObject and RealizePalette functions to update the colors. In some cases, the application may need to deselect, unrealize, select, and realize the logical palette to ensure that the colors are updated exactly as requested. If an application selects a logical palette into more than one device context, changes to the logical palette affect all device contexts for which it is selected.

An application can change the number of entries in a logical palette by using the ResizePalette function. If the application reduces the size, the remaining entries are unchanged. If the application extends the size, the system sets the color for each new entry to black (0, 0, 0) and the flag to zero.

An application can retrieve the color and flag values for entries in a given logical palette by using the GetPaletteEntries function. An application can retrieve the index for the entry in a given logical palette that most closely matches a specified color value by using the GetNearestPaletteIndex function.

When an application no longer needs a logical palette, it can delete it by using the DeleteObject function. The application must make sure the logical palette is no longer selected into a device context before deleting the palette.


Palette Animation

Palette animation is a technique to simulate motion by rapidly changing the colors of selected entries in a color palette. An application can carry out palette animation by creating a logical palette that contains "reserved" entries and then using the AnimatePalette function to change colors in those reserved entries.

An application creates a reserved entry in a logical palette by setting the peFlags member of the PALETTEENTRY structure to the PC_RESERVED flag. Once this logical palette is selected and realized, the application can call the AnimatePalette function to change one or more reserved entries. If the given palette is associated with the active window, the system updates the colors on the screen immediately.


System Palette

The system maintains a system palette for each device that uses palettes. The system palette contains the color values for all colors that can currently be displayed or drawn by the device. Other than viewing the contents of the system palette, applications cannot access the system palette directly. Instead, the system has complete control of the system palette and permits access only through the use of logical palettes.

An application can view the contents of the system palette by using the GetSystemPaletteEntries function. This function retrieves the contents of one or more entries, up to the total number of entries in the system palette. The total is always equal to the number returned for the SIZEPALETTE value by the GetDeviceCaps function and is the same as the maximum size for any given logical palette.

Although applications cannot change colors in the system palette directly, they may cause changes when realizing logical palettes. To realize a palette, the system examines each requested color and attempts to find an entry in the system palette that contains an exact match. If the system finds a matching color, it maps the logical palette index to the corresponding system palette index. If the system does not find an exact match, it copies the requested color to an unused system palette entry before mapping the indexes. If all system palette entries are in use, the system maps the logical palette index to the system palette entry whose color most closely matches the requested color. Once this mapping is set, applications cannot override it. For example, applications cannot use system palette indexes to specify colors; only logical palette indexes are permitted.

Applications can modify the way indexes are mapped by setting the peFlags member of the PALETTEENTRY structure to selected values when creating the logical palette. For example, the PC_NOCOLLAPSE flag directs the system to immediately copy the requested color to an unused system palette entry regardless of whether a system palette entry already contains that color. Also, the PC_EXPLICIT flag directs the system to map the logical palette index to an explicitly given system palette index. (The application gives the system palette index in the low-order word of the PALETTEENTRY structure.)

Palettes can be realized as either a background palette or a foreground palette by specifying TRUE or FALSE respectively for the bForceBackground parameter in the SelectPalette function. There can be only one foreground palette in the system at a time. If the window is the currently active window or a descendent of the currently active window, it can realize a foreground palette. Otherwise the palette is realized as a background palette regardless of the value of the bForceBackground parameter. The critical property of a foreground palette is that, when realized, it can overwrite all entries (except for the static entries) in the system palette. The system accomplishes this by marking all of the entries that are not static in the system palette as unused before the realization of a foreground palette, thereby eliminating all of the used entries. No preprocessing occurs on the system palette for a background palette realization. The foreground palette sets all of the possible nonstatic colors. Background palettes can set only what remains open and are prioritized in a first-come, first-serve manner. Typically, applications use background palettes for child windows which realize their own individual palettes. This helps minimize the number of changes that occur to the system palette.

An unused system palette entry is any entry that is not reserved and does not contain a static color. Reserved entries are explicitly marked with the PC_RESERVED value. These entries are created when an application realizes a logical palette for palette animation. Static color entries are created by the system and correspond to the colors in the default palette. The GetDeviceCaps function can be used to retrieve the NUMRESERVED value, which specifies the number of system palette entries reserved for static colors.

Because the system palette has a limited number of entries, selecting and realizing a logical palette for a given device may affect the colors associated with other logical palettes for the same device. These color changes are especially dramatic when they occur on the display. An application can make sure that reasonable colors are used for its currently selected logical palette by resetting the palette before each use. An application resets the palette by calling the UnrealizeObject and RealizePalette functions. Using these functions causes the system to remap the colors in the logical palette to reasonable colors in the system palette.


System Palette and Static Colors

Ordinarily, the system palette entries that the system reserves for static colors cannot be changed. An application can override this default behavior by using the SetSystemPaletteUse function to reduce the number of static color entries and, thereby, increase the number of unused system palette entries. However, because changing the static colors can have an immediate and dramatic effect on all windows on the display, an application should not call SetSystemPaletteUse, unless it has a maximized window and the input focus.

When an application calls SetSystemPaletteUse with the SYSPAL_NOSTATIC value, the system frees all but two of the reserved entries, allowing those entries to receive new color values when the application subsequently realizes its logical palette. The remaining two static color entries remain reserved and are set to white and black. An application can restore the reserved entries by calling SetSystemPaletteUse with the SYSPAL_STATIC value. It can discover the current system palette usage by using the GetSystemPaletteUse function.

Furthermore, after setting the system palette usage to SYSPAL_NOSTATIC, the application must immediately realize its logical palette, call the GetSysColor function to save the current system color settings, call the SetSysColors function to set the system colors to reasonable values using black and white, and finally send the WM_SYSCOLORCHANGE message to other top-level windows to allow them to be redrawn with the new system colors. When setting system colors using black and white, the application should make sure adjacent or overlapping items, such as window frames and borders, are set to black and white, respectively.

Before the application loses the input focus, closes its window, or terminates, it must immediately call SetSystemPaletteUse with the SYSPAL_STATIC value, realize its logical palette, restore the system colors to their previous values, and send the WM_SYSCOLORCHANGE message. The system sends a WM_PAINT message to any window that is affected by a system color change. Applications that have brushes using the existing system colors should delete those brushes and recreate them using the new system colors.


Palette Messages

Changes to the system palette for the display device can have dramatic and sometimes undesirable effects on the colors used in windows on the desktop. To minimize the impact of these changes, the system provides a set of messages that help applications manage their logical palettes while ensuring that colors in the active window are as close as possible to the colors intended.

the system sends a WM_QUERYNEWPALETTE message to a top-level or overlapped window just before activating the window. This message gives an application the opportunity to select and realize its logical palette so that it receives the best possible mapping of colors for its logical palette. When the application receives the message, it should use the SelectPalette, UnrealizeObject, and RealizePalette functions to select and realize the logical palette. Doing so directs the system to update colors in the system palette so that its colors match as many colors in the logical palette as possible.

When an application causes changes to the system palette as a result of realizing its logical palette, the system sends a WM_PALETTECHANGED message to all top-level and overlapped windows. This message gives applications the opportunity to update the colors in the client areas of their windows, replacing colors that have changed with colors that more closely match the intended colors. An application that receives the WM_PALETTECHANGED message should use UnrealizeObject and RealizePalette to reset the logical palettes associated with all inactive windows and then update the colors in the client area for each inactive window by using the UpdateColors function. This technique does not guarantee the greatest number of exact color matches; however, it does ensure that colors in the logical palette are mapped to reasonable colors in the system palette.

Note To avoid creating an infinite loop, an application should never realize the palette for the window whose handle matches the handle passed in the wParam parameter of the WM_PALETTECHANGED message.

The UpdateColors function typically updates a client area of an inactive window faster than redrawing the area. However, because UpdateColors performs 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. This means UpdateColors cannot be used to update colors when the window becomes active. In such cases, the application should redraw the client area.

the system may send the WM_QUERYNEWPALETTE message when changes to the logical palette are made. Also, the system may send the WM_PALETTEISCHANGING message to all top-level and overlapped windows when the system palette is about to change.


Halftone Palette and Color Adjustment

Halftone palettes are intended to be used whenever the stretching mode of a device context is set to HALFTONE. An application creates a halftone palette by using the CreateHalftonePalette function. The application must select and realize this palette into the device context before calling the StretchBlt or StretchDIBits function.

The system automatically adjusts the input color of source bitmaps whenever applications call the StretchBlt and StretchDIBits functions and the stretching mode of a device context is set to HALFTONE. These color adjustments affect certain attributes of the image, such as contrast and brightness. An application can set the color adjustment values by using the SetColorAdjustment function. The application can retrieve the color adjustment values for the specified device context by using the GetColorAdjustment function.


Using Color

  • Enumerating Colors
  • Creating Colored Pens and Brushes


Enumerating Colors

You can determine how many colors a device supports and what those colors are by retrieving the count of colors for the device and enumerating the colors of the solid pens. To retrieve the number of colors, use the GetDeviceCaps function with the NUMCOLORS value. To enumerate solid pens, use the EnumObjects function and a corresponding callback function that receives information about each pen.

// GetTheColors - returns the count and color values of solid colors
// Returns a pointer to the array containing colors
// hdc - handle to device context

COLORREF *GetTheColors(HDC hdc)
{
    int cColors;
    COLORREF *aColors;

    // Get the number of colors.
    cColors = GetDeviceCaps(hdc, NUMCOLORS);

    // Allocate space for the array.
    aColors = (COLORREF *)LocalAlloc(LPTR, sizeof(COLORREF) *
        (cColors+1));

    // Save the count of colors in first element.
    aColors[0] = (LONG)cColors;

    // Enumerate all pens and save solid colors in the array.
    EnumObjects(hdc, OBJ_PEN, (GOBJENUMPROC)MyEnumProc, (LONG)aColors);

    // Refresh the count of colors.
    aColors[0] = (LONG)cColors;

    return aColors;
}

int MyEnumProc(LPVOID lp, LPBYTE lpb)
{
    LPLOGPEN lopn;
    COLORREF *aColors;
    int iColor;

    lopn = (LPLOGPEN)lp;
    aColors = (COLORREF *)lpb;

    if (lopn->lopnStyle==PS_SOLID)
    {
        // Check for too many colors.
        if ((iColor = (int)aColors[0]) <= 0)
             return 0;
        aColors[iColor] = lopn->lopnColor;
        aColors[0]--;
    }
    return 1;
}


Creating Colored Pens and Brushes

Although you can specify any color for a pen when creating it, the system uses only colors that are available on the device. This means the system uses the closest matching color when it realizes the pen for drawing. When creating brushes, the system generates a dithered color if you specify a color that the device does not support. In either case, you can use the RGB macro to specify a color when creating a pen or brush.

// DrawARectangle - draws a red rectangle with a green border
// No return value.
// hdc - handle to the device context

void DrawARectangle(HDC hdc)
{
    HPEN hpen, hpenOld;
    HBRUSH hbrush, hbrushOld;

    // Create a green pen.
    hpen = CreatePen(PS_SOLID, 10, RGB(0, 255, 0));
    // Create a red brush.
    hbrush = CreateSolidBrush(RGB(255, 0, 0));

    // Select the new pen and brush, and then draw.
    hpenOld = SelectObject(hdc, hpen);
    hbrushOld = SelectObject(hdc, hbrush);
    Rectangle(hdc, 100,100, 200,200);

    // Do not forget to clean up.
    SelectObject(hdc, hpenOld);
    DeleteObject(hpen);
    SelectObject(hdc, hbrushOld);
    DeleteObject(hbrush);
}


Color Reference

The following elements are associated with color.

  • Color Functions
  • Color Structures
  • Color Macros
  • Color Messages


Color Functions

The following functions are used with color.

Function | Description
AnimatePalette | Replaces entries in the specified logical palette.
CreateHalftonePalette | Creates a halftone palette for the specified device context (DC).
CreatePalette | Creates a logical palette.
GetColorAdjustment | Retrieves the color adjustment values for the specified DC.
GetNearestColor | Retrieves a color value identifying a color from the system palette that will be displayed when the specified color value is used.
GetNearestPaletteIndex | Retrieves the index for the entry in the specified logical palette most closely matching a specified color value.
GetPaletteEntries | Retrieves a specified range of palette entries from the given logical palette.
GetSystemPaletteEntries | Retrieves a range of palette entries from the system palette that is associated with the specified DC.
GetSystemPaletteUse | Retrieves the current state of the system (physical) palette for the specified DC.
RealizePalette | Maps palette entries from the current logical palette to the system palette.
ResizePalette | Increases or decreases the size of a logical palette based on the specified value.
SelectPalette | Selects the specified logical palette into a device context.
SetColorAdjustment | Sets the color adjustment values for a DC using the specified values.
SetPaletteEntries | Sets RGB (red, green, blue) color values and flags in a range of entries in a logical palette.
SetSystemPaletteUse | Allows an application to specify whether the system palette contains 2 or 20 static colors.
UnrealizeObject | Resets the origin of a brush or resets a logical palette.
UpdateColors | Updates the client area of the specified device context by remapping the current colors in the client area to the currently realized logical palette.


AnimatePalette

The AnimatePalette function replaces entries in the specified logical palette.

BOOL AnimatePalette(
  HPALETTE hpal,           // handle to logical palette
  UINT iStartIndex,        // first entry in logical palette
  UINT cEntries,           // number of entries
  CONST PALETTEENTRY *ppe  // first replacement
);

Parameters

hpal
[in] Handle to the logical palette.
iStartIndex
[in] Specifies the first logical palette entry to be replaced.
cEntries
[in] Specifies the number of entries to be replaced.
ppe
[in] Pointer to the first member in an array of PALETTEENTRY structures used to replace the current entries.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

The AnimatePalette function only changes entries with the PC_RESERVED flag set in the corresponding palPalEntry member of the LOGPALETTE structure.

If the given palette is associated with the active window, the colors in the palette are replaced immediately.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, CreatePalette, GetDeviceCaps, LOGPALETTE, PALETTEENTRY


CreateHalftonePalette

The CreateHalftonePalette function creates a halftone palette for the specified device context (DC).

HPALETTE CreateHalftonePalette(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is a handle to a logical halftone palette.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application should create a halftone palette when the stretching mode of a device context is set to HALFTONE. The logical halftone palette returned by CreateHalftonePalette should then be selected and realized into the device context before the StretchBlt or StretchDIBits function is called.

When you no longer need the palette, call the DeleteObject function to delete it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, DeleteObject, RealizePalette, SelectPalette, SetStretchBltMode, StretchDIBits, StretchBlt


CreatePalette

The CreatePalette function creates a logical palette.

HPALETTE CreatePalette(
  CONST LOGPALETTE *lplgpl   // logical palette
);

Parameters

lplgpl
[in] Pointer to a LOGPALETTE structure that contains information about the colors in the logical palette.

Return Values

If the function succeeds, the return value is a handle to a logical palette.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Once an application creates a logical palette, it can select that palette into a device context by calling the SelectPalette function. A palette selected into a device context can be realized by calling the RealizePalette function.

When you no longer need the palette, call the DeleteObject function to delete it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, DeleteObject, GetDeviceCaps, LOGPALETTE, RealizePalette, SelectPalette


GetColorAdjustment

The GetColorAdjustment function retrieves the color adjustment values for the specified device context (DC).

BOOL GetColorAdjustment(
  HDC hdc,                 // handle to DC
  LPCOLORADJUSTMENT lpca   // color adjustment values
);

Parameters

hdc
[in] Handle to the device context.
lpca
[out] Pointer to a COLORADJUSTMENT structure that receives the color adjustment values.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, SetColorAdjustment, COLORADJUSTMENT


GetNearestColor

The GetNearestColor function retrieves a color value identifying a color from the system palette that will be displayed when the specified color value is used.

COLORREF GetNearestColor(
  HDC hdc,           // handle to DC
  COLORREF crColor   // color to be matched
);

Parameters

hdc
[in] Handle to the device context.
crColor
[in] Specifies a color value that identifies a requested color. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value identifies a color from the system palette that corresponds to the given color value.

If the function fails, the return value is CLR_INVALID.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetNearestPaletteIndex, COLORREF, RGB


GetNearestPaletteIndex

The GetNearestPaletteIndex function retrieves the index for the entry in the specified logical palette most closely matching a specified color value.

UINT GetNearestPaletteIndex(
  HPALETTE hpal,     // handle to logical palette
  COLORREF crColor   // color to be matched
);

Parameters

hpal
[in] Handle to a logical palette.
crColor
[in] Specifies a color to be matched. To create a COLORREF color value, use the RGB macro.

Return Values

If the function succeeds, the return value is the index of an entry in a logical palette.

If the function fails, the return value is CLR_INVALID.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If the given logical palette contains entries with the PC_EXPLICIT flag set, the return value is undefined.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetNearestColor, GetPaletteEntries, GetSystemPaletteEntries, COLORREF, RGB


GetPaletteEntries

The GetPaletteEntries function retrieves a specified range of palette entries from the given logical palette.

UINT GetPaletteEntries(
  HPALETTE hpal,        // handle to logical palette
  UINT iStartIndex,     // first entry to retrieve
  UINT nEntries,        // number of entries to retrieve
  LPPALETTEENTRY lppe   // array that receives entries
);

Parameters

hpal
[in] Handle to the logical palette.
iStartIndex
[in] Specifies the first entry in the logical palette to be retrieved.
nEntries
[in] Specifies the number of entries in the logical palette to be retrieved.
lppe
[out] Pointer to an array of PALETTEENTRY structures to receive the palette entries. The array must contain at least as many structures as specified by the nEntries parameter.

Return Values

If the function succeeds and the handle to the logical palette is a valid pointer (not NULL), the return value is the number of entries retrieved from the logical palette. If the function succeeds and handle to the logical palette is NULL, the return value is the number of entries in the given palette.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If the nEntries parameter specifies more entries than exist in the palette, the remaining members of the PALETTEENTRY structure are not altered.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetSystemPaletteEntries, SetPaletteEntries, PALETTEENTRY


GetSystemPaletteEntries

The GetSystemPaletteEntries function retrieves a range of palette entries from the system palette that is associated with the specified device context (DC).

UINT GetSystemPaletteEntries(
  HDC hdc,              // handle to DC
  UINT iStartIndex,     // first entry to be retrieved
  UINT nEntries,        // number of entries to be retrieved
  LPPALETTEENTRY lppe   // array that receives entries
);

Parameters

hdc
[in] Handle to the device context.
iStartIndex
[in] Specifies the first entry to be retrieved from the system palette.
nEntries
[in] Specifies the number of entries to be retrieved from the system palette.
lppe
[out] Pointer to an array of PALETTEENTRY structures to receive the palette entries. The array must contain at least as many structures as specified by the nEntries parameter. If this parameter is NULL, the function returns the total number of entries in the palette.

Return Values

If the function succeeds, the return value is the number of entries retrieved from the palette.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetPaletteEntries, PALETTEENTRY


GetSystemPaletteUse

The GetSystemPaletteUse function retrieves the current state of the system (physical) palette for the specified device context (DC).

UINT GetSystemPaletteUse(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the current state of the system palette. This parameter can be one of the following values.

Value | Meaning
SYSPAL_NOSTATIC | The system palette contains no static colors except black and white.
SYSPAL_STATIC | The system palette contains static colors that will not change when an application realizes its logical palette.
SYSPAL_ERROR | The given device context is invalid or does not support a color palette.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

By default, the system palette contains 20 static colors that are not changed when an application realizes its logical palette. An application can gain access to most of these colors by calling the SetSystemPaletteUse function.

The device context identified by the hdc parameter must represent a device that supports color palettes.

An application can determine whether or not a device supports color palettes by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, SetSystemPaletteUse


RealizePalette

The RealizePalette function maps palette entries from the current logical palette to the system palette.

UINT RealizePalette(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context into which a logical palette has been selected.

Return Values

If the function succeeds, the return value is the number of entries in the logical palette mapped to the system palette.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

The RealizePalette function modifies the palette for the device associated with the specified device context. If the device context is a memory DC, the color table for the bitmap selected into the DC is modified. If the device context is a display DC, the physical palette for that device is modified.

A logical palette is a buffer between color-intensive applications and the system, allowing these applications to use as many colors as needed without interfering with colors displayed by other windows.

When an application's window has the focus and it calls the RealizePalette function, the system attempts to realize as many of the requested colors as possible. The same is also true for applications with inactive windows.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, CreatePalette, GetDeviceCaps, SelectPalette


ResizePalette

The ResizePalette function increases or decreases the size of a logical palette based on the specified value.

BOOL ResizePalette(
  HPALETTE hpal, // handle to logical palette
  UINT nEntries  // number of entries in logical palette
);

Parameters

hpal
[in] Handle to the palette to be changed.
nEntries
[in] Specifies the number of entries in the palette after it has been resized. Windows NT/2000 or later: the number of entries is limited to 1024.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

If an application calls ResizePalette to reduce the size of the palette, the entries remaining in the resized palette are unchanged. If the application calls ResizePalette to enlarge the palette, the additional palette entries are set to black (the red, green, and blue values are all 0) and their flags are set to zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps


SelectPalette

The SelectPalette function selects the specified logical palette into a device context.

HPALETTE SelectPalette(
  HDC hdc,                // handle to DC
  HPALETTE hpal,          // handle to logical palette
  BOOL bForceBackground   // foreground or background mode
);

Parameters

hdc
[in] Handle to the device context.
hpal
[in] Handle to the logical palette to be selected.
bForceBackground
[in] Specifies whether the logical palette is forced to be a background palette. If this value is TRUE, the RealizePalette function causes the logical palette to be mapped to the colors already in the physical palette in the best possible way. This is always done, even if the window for which the palette is realized belongs to a thread without active focus.

If this value is FALSE, RealizePalette causes the logical palette to be copied into the device palette when the application is in the foreground. (If the hdc parameter is a memory device context, this parameter is ignored.)

Return Values

If the function succeeds, the return value is a handle to the device context's previous logical palette.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

An application can select a logical palette into more than one device context only if device contexts are compatible. Otherwise SelectPalette fails. To create a device context that is compatible with another device context, call CreateCompatibleDC with the first device context as the parameter. If a logical palette is selected into more than one device context, changes to the logical palette will affect all device contexts for which it is selected.

An application might call the SelectPalette function with the bForceBackground parameter set to TRUE if the child windows of a top-level window each realize their own palettes. However, only the child window that needs to realize its palette must set bForceBackground to TRUE; other child windows must set this value to FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, CreateCompatibleDC, CreatePalette, GetDeviceCaps, RealizePalette


SetColorAdjustment

The SetColorAdjustment function sets the color adjustment values for a device context (DC) using the specified values.

BOOL SetColorAdjustment(
  HDC hdc,                     // handle to DC
  CONST COLORADJUSTMENT *lpca  // color adjustment values
);

Parameters

hdc
[in] Handle to the device context.
lpca
[in] Pointer to a COLORADJUSTMENT structure containing the color adjustment values.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The color adjustment values are used to adjust the input color of the source bitmap for calls to the StretchBlt and StretchDIBits functions when HALFTONE mode is set.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetColorAdjustment, StretchBlt, StretchDIBits, SetStretchBltMode, COLORADJUSTMENT


SetPaletteEntries

The SetPaletteEntries function sets RGB (red, green, blue) color values and flags in a range of entries in a logical palette.

UINT SetPaletteEntries(
  HPALETTE hpal,             // handle to logical palette
  UINT iStart,               // index of first entry to set
  UINT cEntries,             // number of entries to set
  CONST PALETTEENTRY *lppe   // array of palette entries
);

Parameters

hpal
[in] Handle to the logical palette.
iStart
[in] Specifies the first logical-palette entry to be set.
cEntries
[in] Specifies the number of logical-palette entries to be set.
lppe
[in] Pointer to the first member of an array of PALETTEENTRY structures containing the RGB values and flags.

Return Values

If the function succeeds, the return value is the number of entries that were set in the logical palette.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether or not a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

Even if a logical palette has been selected and realized, changes to the palette do not affect the physical palette in the surface. RealizePalette must be called again to set the new logical palette into the surface.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetPaletteEntries, RealizePalette, PALETTEENTRY


SetSystemPaletteUse

The SetSystemPaletteUse function allows an application to specify whether the system palette contains 2 or 20 static colors. The default system palette contains 20 static colors. (Static colors cannot be changed when an application realizes a logical palette.)

UINT SetSystemPaletteUse(
  HDC hdc,      // handle to DC
  UINT uUsage   // palette usage
);

Parameters

hdc
[in] Handle to the device context. This device context must refer to a device that supports color palettes.
uUsage
[in] Specifies the new use of the system palette. This parameter can be one of the following values.
Value | Meaning
SYSPAL_NOSTATIC | The system palette contains two static colors (black and white).
SYSPAL_NOSTATIC256 | Windows 2000 or later: The system palette contains no static colors.
SYSPAL_STATIC | The system palette contains static colors that will not change when an application realizes its logical palette.

Return Values

If the function succeeds, the return value is the previous system palette. It can be either SYSPAL_NOSTATIC, SYSPAL_NOSTATIC256, or SYSPAL_STATIC.

If the function fails, the return value is SYSPAL_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

When an application window moves to the foreground and the SYSPAL_NOSTATIC value is set, the application must call the GetSysColor function to save the current system colors setting. It must also call SetSysColors to set reasonable values using only black and white. When the application returns to the background or terminates, the previous system colors must be restored.

If the function returns SYSPAL_ERROR, the specified device context is invalid or does not support color palettes.

An application must call this function only when its window is maximized and has the input focus.

If an application calls SetSystemPaletteUse with uUsage set to SYSPAL_NOSTATIC, the system continues to set aside two entries in the system palette for pure white and pure black, respectively.

After calling this function with uUsage set to SYSPAL_NOSTATIC, an application must take the following steps:

  1. Realize the logical palette.
  2. Call the GetSysColor function to save the current system-color settings.
  3. Call the SetSysColors function to set the system colors to reasonable values using black and white. For example, adjacent or overlapping items (such as window frames and borders) should be set to black and white, respectively.
  4. Send the WM_SYSCOLORCHANGE message to other top-level windows to allow them to be redrawn with the new system colors.

When the application's window loses focus or closes, the application must perform the following steps:

  1. Call SetSystemPaletteUse with the uUsage parameter set to SYSPAL_STATIC.
  2. Realize the logical palette.
  3. Restore the system colors to their previous values.
  4. Send the WM_SYSCOLORCHANGE message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, GetSysColor, SetSysColors, GetSystemPaletteUse


UnrealizeObject

The UnrealizeObject function resets the origin of a brush or resets a logical palette. If the hgdiobj parameter is a handle to a brush, UnrealizeObject directs the system to reset the origin of the brush the next time it is selected. If the hgdiobj parameter is a handle to a logical palette, UnrealizeObject directs the system to realize the palette as though it had not previously been realized. The next time the application calls the RealizePalette function for the specified palette, the system completely remaps the logical palette to the system palette.

BOOL UnrealizeObject(
  HGDIOBJ hgdiobj   // handle to logical palette
);

Parameters

hgdiobj
[in] Handle to the logical palette to be reset.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The UnrealizeObject function should not be used with stock objects. For example, the default palette, obtained by calling GetStockObject(DEFAULT_PALETTE), is a stock object.

A palette identified by hgdiobj can be the currently selected palette of a device context.

Windows 95/98/Me: Automatic tracking of the brush origin is not supported. Applications must use the UnrealizeObject, SetBrushOrgEx, and SelectObject functions to align the brush before using it.

Windows 2000 or later: If hgdiobj is a brush, UnrealizeObject does nothing, and the function returns TRUE. Use SetBrushOrgEx to set the origin of a brush.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetStockObject, RealizePalette, SetBrushOrgEx


UpdateColors

The UpdateColors function updates the client area of the specified device context by remapping the current colors in the client area to the currently realized logical palette.

BOOL UpdateColors(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can determine whether a device supports palette operations by calling the GetDeviceCaps function and specifying the RASTERCAPS constant.

An inactive window with a realized logical palette may call UpdateColors as an alternative to redrawing its client area when the system palette changes.

The UpdateColors function typically updates a client area faster than redrawing the area. However, because UpdateColors 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.

This function must be called soon after a WM_PALETTECHANGED message is received.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Colors Overview, Color Functions, GetDeviceCaps, RealizePalette


Color Structures

The following structures are used with color.

COLORREF
LOGPALETTE
PALETTEENTRY


COLORREF

The COLORREF value is used to specify an RGB color.

typedef DWORD COLORREF;
typedef DWORD *LPCOLORREF;

Remarks

When specifying an explicit RGB color, the COLORREF value has the following hexadecimal form:

0x00bbggrr

The low-order byte contains a value for the relative intensity of red; the second byte contains a value for green; and the third byte contains a value for blue. The high-order byte must be zero. The maximum value for a single byte is 0xFF.

To create a COLORREF color value, use the RGB macro. To extract the individual values for the red, green, and blue components of a color value, use the GetRValue, GetGValue, and GetBValue macros, respectively.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Colors Overview, Color Structures, GetBValue, GetGValue, GetRValue, RGB


LOGPALETTE

The LOGPALETTE structure defines a logical palette.

typedef struct tagLOGPALETTE {
  WORD         palVersion;
  WORD         palNumEntries;
  PALETTEENTRY palPalEntry[1];
} LOGPALETTE;

Members

palVersion
Specifies the version number of the system.
palNumEntries
Specifies the number of entries in the logical palette.
palPalEntry
Specifies an array of PALETTEENTRY structures that define the color and usage of each entry in the logical palette.

Remarks

The colors in the palette-entry table should appear in order of importance because entries earlier in the logical palette are most likely to be placed in the system palette.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Structures, CreatePalette, PALETTEENTRY


PALETTEENTRY

The PALETTEENTRY structure specifies the color and usage of an entry in a logical palette. A logical palette is defined by a LOGPALETTE structure.

typedef struct tagPALETTEENTRY {
  BYTE peRed;
  BYTE peGreen;
  BYTE peBlue;
  BYTE peFlags;
} PALETTEENTRY;

Members

peRed
Specifies a red intensity value for the palette entry.
peGreen
Specifies a green intensity value for the palette entry.
peBlue
Specifies a blue intensity value for the palette entry.
peFlags
Specifies how the palette entry is to be used. The peFlags member may be set to NULL or one of the following values:
Value | Meaning
PC_EXPLICIT | Specifies that the low-order word of the logical palette entry designates a hardware palette index. This flag allows the application to show the contents of the display device palette.
PC_NOCOLLAPSE | Specifies that the color be placed in an unused entry in the system palette instead of being matched to an existing color in the system palette. If there are no unused entries in the system palette, the color is matched normally. Once this color is in the system palette, colors in other logical palettes can be matched to this color.
PC_RESERVED | Specifies that the logical palette entry be used for palette animation. This flag prevents other windows from matching colors to the palette entry since the color frequently changes. If an unused system-palette entry is available, the color is placed in that entry. Otherwise, the color is not available for animation.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Structures, LOGPALETTE


Color Macros

The following macros are used with color.

GetBValue
GetGValue
GetRValue
PALETTEINDEX
PALETTERGB
RGB


GetBValue

The GetBValue macro retrieves an intensity value for the blue component of a red, green, blue (RGB) value.

BYTE GetBValue(
  DWORD rgb     // RGB value
);

Parameters

rgb
Specifies an RGB color value.

Return Values

The return value is the intensity of the blue component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, GetGValue, GetRValue, PALETTEINDEX, PALETTERGB, RGB


GetGValue

The GetGValue macro retrieves an intensity value for the green component of a red, green, blue (RGB) value.

BYTE GetGValue(
  DWORD rgb     // RGB value
);

Parameters

rgb
Specifies an RGB color value.

Return Values

The return value is the intensity of the green component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, GetBValue, GetRValue, PALETTEINDEX, PALETTERGB, RGB


GetRValue

The GetRValue macro retrieves an intensity value for the red component of a red, green, blue (RGB) value.

BYTE GetRValue(
  DWORD rgb  // RGB value
);

Parameters

rgb
Specifies an RGB color value.

Return Values

The return value is the intensity of the red component of the specified RGB color.

Remarks

The intensity value is in the range 0 through 255.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, GetBValue, GetGValue, PALETTEINDEX, PALETTERGB, RGB


PALETTEINDEX

The PALETTEINDEX macro accepts an index to a logical-color palette entry and returns a palette-entry specifier consisting of a COLORREF value that specifies the color associated with the given index. An application using a logical palette can pass this specifier, instead of an explicit red, green, blue (RGB) value, to GDI functions that expect a color. This allows the function to use the color in the specified palette entry.

COLORREF PALETTEINDEX(
  WORD wPaletteIndex  // index to palette entry
);

Parameters

wPaletteIndex
Specifies an index to the palette entry containing the color to be used for a graphics operation.

Return Values

The return value is a logical-palette index specifier.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, COLORREF, PALETTERGB, RGB


PALETTERGB

The PALETTERGB macro accepts three values that represent the relative intensities of red, green, and blue and returns a palette-relative red, green, blue (RGB) specifier consisting of 2 in the high-order byte and an RGB value in the three low-order bytes. An application using a color palette can pass this specifier, instead of an explicit RGB value, to functions that expect a color.

COLORREF PALETTERGB(
  BYTE bRed,    // red component of palette-relative RGB
  BYTE bGreen,  // green component of palette-relative RGB
  BYTE bBlue    // blue component of palette-relative RGB
);

Parameters

bRed
Specifies the intensity of the red color field.
bGreen
Specifies the intensity of the green color field.
bBlue
Specifies the intensity of the blue color field.

Return Values

The return value is a palette-relative RGB specifier. For output devices that support logical palettes, the system matches a palette-relative RGB value to the nearest color in the logical palette of the device context as though the application had specified an index to that palette entry. If an output device does not support a system palette, the system uses the palette-relative RGB as though it were a conventional RGB value returned by the RGB macro.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, COLORREF, PALETTEINDEX, RGB


RGB

The RGB macro selects a red, green, blue (RGB) color based on the arguments supplied and the color capabilities of the output device.

COLORREF RGB(
  BYTE byRed,    // red component of color
  BYTE byGreen,  // green component of color
  BYTE byBlue    // blue component of color
);

Parameters

byRed
Specifies the intensity of the red color.
byGreen
Specifies the intensity of the green color.
byBlue
Specifies the intensity of the blue color.

Return Values

The return value is the resultant RGB color as a COLORREF value.

Remarks

The intensity for each argument is in the range 0 through 255. If all three intensities are zero, the result is black. If all three intensities are 255, the result is white.

To extract the individual values for the red, green, and blue components of a COLORREF color value, use the GetRValue, GetGValue, and GetBValue macros, respectively.

When creating or examining a logical palette, use the RGBQUAD structure to define color values and examine individual component values. For more information about using color values in a color palette, see the descriptions of the PALETTEINDEX and PALETTERGB macros.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Colors Overview, Color Macros, COLORREF, GetBValue, GetGValue, GetRValue, PALETTEINDEX, PALETTERGB, RGBQUAD


Color Messages

The following messages are used with color.

WM_PALETTECHANGED
WM_PALETTEISCHANGING
WM_QUERYNEWPALETTE
WM_SYSCOLORCHANGE


WM_PALETTECHANGED

The WM_PALETTECHANGED message is sent to all top-level and overlapped windows after the window with the keyboard focus has realized its logical palette, thereby changing the system palette. This message enables a window that uses a color palette but does not have the keyboard focus to realize its logical palette and update its client area.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PALETTECHANGED
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the window that caused the system palette to change.
lParam
This parameter is not used.

Remarks

This message must be sent to all top-level and overlapped windows, including the one that changed the system palette. If any child windows use a color palette, this message must be passed on to them as well.

To avoid creating an infinite loop, a window that receives this message must not realize its palette, unless it determines that wParam does not contain its own window handle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Colors Overview, Color Messages, WM_PALETTEISCHANGING, WM_QUERYNEWPALETTE


WM_PALETTEISCHANGING

The WM_PALETTEISCHANGING message informs applications that an application is going to realize its logical palette.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PALETTEISCHANGING
  WPARAM wParam,   // handle to window (HWND)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the window that is going to realize its logical palette.
lParam
This parameter is not used.

Return Values

If an application processes this message, it should return zero.

Remarks

The application changing its palette does not wait for acknowledgment of this message before changing the palette and sending the WM_PALETTECHANGED message. As a result, the palette may already be changed by the time an application receives this message.

If the application either ignores or fails to process this message and a second application realizes its palette while the first is using palette indexes, there is a strong possibility that the user will see unexpected colors during subsequent drawing operations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Colors Overview, Color Messages, WM_PALETTECHANGED, WM_QUERYNEWPALETTE


WM_QUERYNEWPALETTE

The WM_QUERYNEWPALETTE message informs a window that it is about to receive the keyboard focus, giving the window the opportunity to realize its logical palette when it receives the focus.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_QUERYNEWPALETTE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

If the window realizes its logical palette, it must return TRUE; otherwise, it must return FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Colors Overview, Color Messages, WM_PALETTECHANGED, WM_PALETTEISCHANGING


WM_SYSCOLORCHANGE

The WM_SYSCOLORCHANGE message is sent to all top-level windows when a change is made to a system color setting.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYSCOLORCHANGE
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Remarks

The system sends a WM_PAINT message to any window that is affected by a system color change.

Applications that have brushes using the existing system colors should delete those brushes and recreate them using the new system colors.

Top level windows that use common controls must forward the WM_SYSCOLORCHANGE message to the controls; otherwise, the controls will not be notified of the color change. This ensures that the colors used by your common controls are consistent with those used by other user interface objects. For example, a toolbar control uses the "3D Objects" color to draw its buttons. If the user changes the 3D Objects color but the WM_SYSCOLORCHANGE message is not forwarded to the toolbar, the toolbar buttons will remain in their original color while the color of other buttons in the system changes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Colors Overview, Color Messages, WM_PAINT


Coordinate Spaces and Transformations

Win32®-based applications use coordinate spaces and transformations to scale, rotate, translate, shear, and reflect graphics output. A coordinate space is a planar space that locates two-dimensional objects by using two reference axes that are perpendicular to each other. There are four coordinate spaces: world, page, device, and physical device (client area, desktop, or page of printer paper).

A transformation is an algorithm that alters ("transforms") the size, orientation, and shape of objects. Transformations also transfer a graphics object from one coordinate space to another. Ultimately, the object appears on the physical device, which is usually a screen or printer.

This chapter is divided into three topics:

  • About Coordinate Spaces and Transformations
  • Using Coordinate Spaces and Transformations
  • Coordinate Space and Transformation Reference


About Coordinate Spaces and Transformations

Coordinate spaces and transformations are used by the following types of applications:

  • Desktop publishing applications (to "zoom" parts of a page or to display adjacent pages in a window).
  • Computer-aided design (CAD) applications (to rotate objects, scale drawings, or create perspective views).
  • Spreadsheet applications (to move and size graphs).

The following illustrations show successive views of an object created in a drawing application. The first illustration shows the object as it appears in the original drawing; the succeeding five illustrations show the effects of applying various transformations.


Transformation of Coordinate Spaces

A coordinate space is a planar space based on the Cartesian coordinate system. This system provides a means of specifying the location of each point on a plane. It requires two axes that are perpendicular and equal in length. The following illustration shows a coordinate space.

The system supports four coordinate spaces, as described in the following table.

Coordinate space | Description
world | Used optionally as the starting coordinate space for graphics transformations. It allows scaling, translation, rotation, shearing, and reflection. World space measures 2^32 units high by 2^32 units wide.
page | Used either as the next space after world space or as the starting space for graphics transformations. It sets the mapping mode. Page space (referred to as logical space in 16-bit versions of Windows) also measures 2^32 units high by 2^32 units wide.
device | Used as the next space after page space. It only allows translation, which ensures the origin of the device space maps to the proper location in physical device space. Device space measures 2^27 units high by 2^27 units wide.
physical device | The final (output) space for graphics transformations. It usually refers to the client area of the application window; however, it can also include the entire desktop, a complete window (including the frame, title bar, and menu bar), or a page of printer or plotter paper, depending on the function that obtained the handle for the device context. Physical device dimensions vary according to the dimensions set by the display, printer, or plotter technology.

Page space works with device space to provide applications with device-independent units, such as millimeters and inches. This overview refers to both world space and page space as logical space.

To depict output on a physical device, the system copies (or maps) a rectangular region from one coordinate space into the next using a transformation until the output appears in its entirety on the physical device. Mapping begins in the application's world space if the application has called the SetWorldTransform function; otherwise, mapping occurs in page space. As the system copies each point within the rectangular region from one space into another, it applies an algorithm called a transformation. A transformation alters (or transforms) the size, orientation, and shape of objects that are copied from one coordinate space into another. Although a transformation affects an object as a whole, it is applied to each point, or to each line, in the object.

The following illustration shows a typical transformation performed by using the SetWorldTransform function.


World-Space to Page-Space Transformations

World-space to page-space transformations support translation and scaling. In addition, they support rotation, shear, and reflection capabilities. The following sections describe these transformations, illustrate their effects, and provide the algorithms used to achieve them.

  • Translation
  • Scaling
  • Rotation
  • Shear
  • Reflection
  • Combined World-to-Page Space Transformations


Translation

Some applications translate (or shift) objects drawn in the client area. by calling the SetWorldTransform function to set the appropriate world-space to page-space transformation. The SetWorldTransform function receives a pointer to an XFORM structure containing the appropriate values. The eDx and eDy members of XFORM specify the horizontal and vertical translation components, respectively.

When translation occurs, each point in an object is shifted vertically, horizontally, or both, by a specified amount. The following illustration shows a 20- by 20-unit rectangle that was translated to the right by 10 units when copied from world-coordinate space to page-coordinate space.

In the preceding illustration, the x-coordinate of each point in the rectangle is 10 units greater than the original x-coordinate.

Horizontal translation can be represented by the following algorithm.

x' = x + Dx

Where x' is the new x-coordinate, x is the original x-coordinate, and Dx is the horizontal distance moved.

Vertical translation can be represented by the following algorithm.

y' = y + Dy

Where y' is the new y-coordinate, y is the original y-coordinate, and Dy is the vertical distance moved.

The horizontal and vertical translation transformations can be combined into a single operation by using a 3-by-3 matrix.

                      |1   0   0|
|x' y' 1| = |x y 1| * |0   1   0|
                      |Dx  Dy  1|

(The rules of matrix multiplication state that the number of rows in one matrix must equal the number of columns in the other. The integer 1 in the matrix |x y 1| is a placeholder that was added to meet this requirement.)

The 3-by-3 matrix that produced the illustrated translation transformation contains the following values.

|1  0  0|
|0  1  0|
|10 0  1|


Scaling

Most CAD and drawing applications provide features that scale output created by the user. Applications that include scaling (or zoom) capabilities call the SetWorldTransform function to set the appropriate world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11 and eM22 members of XFORM specify the horizontal and vertical scaling components, respectively.

When scaling occurs, the vertical and horizontal lines (or vectors), that constitute an object, are stretched or compressed with respect to the x- or y-axis. The following illustration shows a 20-by-20-unit rectangle scaled vertically to twice its original height when copied from world-coordinate space to page-coordinate space.

In the preceding illustration, the vertical lines that define the original rectangle's side measure 20 units, while the vertical lines that define the scaled rectangle's sides measure 40 units.

Vertical scaling can be represented by the following algorithm.

y' = y * Dy

Where y' is the new length, y is the original length, and Dy is the vertical scaling factor.

Horizontal scaling can be represented by the following algorithm.

x' = x * Dx

Where x' is the new length, x is the original length, and Dx is the horizontal scaling factor.

The vertical and horizontal scaling transformations can be combined into a single operation by using a 2-by-2 matrix.

|x' y'|  =  |Dx   0|  *  |x y|
            |0   Dy|

The 2-by-2 matrix that produced the scaling transformation contains the following values.

|1    0|
|0    2|


Rotation

Many CAD applications provide features that rotate objects drawn in the client area. Applications that include rotation capabilities use the SetWorldTransform function to set the appropriate world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11, eM12, eM21, and eM22 members of XFORM specify respectively, the cosine, sine, negative sine, and cosine of the angle of rotation.

When rotation occurs, the points that constitute an object are rotated with respect to the coordinate-space origin. The following illustration shows a 20-by-20-unit rectangle rotated 30 degrees when copied from world-coordinate space to page-coordinate space.

In the preceding illustration, each point in the rectangle was rotated 30 degrees with respect to the coordinate-space origin.

The following algorithm computes the new x-coordinate (x') for a point (x,y) that is rotated by angle A with respect to the coordinate-space origin.

x' = (x * cos A) - (y * sin A)

The following algorithm computes the y-coordinate (y') for a point (x,y) that is rotated by the angle A with respect to the origin.

y' = (x * sin A) + (y * cos A)

The two rotation transformations can be combined in a 2-by-2 matrix as follows.

|x' y'| == |x y| * | cos A   sin A|
                   |-sin A   cos A|

The 2-by-2 matrix that produced the rotation contains the following values.

| .8660    .5000|
|-.5000    .8660|

Rotation Algorithm Derivation

Rotation algorithms are based on trigonometry's addition theorem stating that the trigonometric function of a sum of two angles (A1 and A2) can be expressed in terms of the trigonometric functions of the two angles.

sin(A1 + A2) = (sin A1 * cos A2) + (cos A1 * sin A2)
cos(A1 + A2) = (cos A1 * cos A2) - (sin A1 * sin A2)

The following illustration shows a point p rotated counterclockwise to a new position p'. In addition, it shows two triangles formed by a line drawn from the coordinate-space origin to each point and a line drawn from each point through the x-axis.

Using trigonometry, the x-coordinate of point p can be obtained by multiplying the length of the hypotenuse h by the cosine of A1.

x = h * cos A1

The y-coordinate of point p can be obtained by multiplying the length of the hypotenuse h by the sine of A1.

y = h * sin A1

Likewise, the x-coordinate of point p' can be obtained by multiplying the length of the hypotenuse h by the cosine of (A1 + A2).

x' = h * cos (A1 + A2)

Finally, the y-coordinate of point p' can be obtained by multiplying the length of the hypotenuse h by the sine of (A1 + A2).

y' = h * sin (A1 + A2)

Using the addition theorem, the preceding algorithms become the following:

x' = (h * cos A1 * cos A2) - (h * sin A1 * sin A2)
y' = (h * cos A1 * sin A2) + (h * sin A1 * cos A2)

The rotation algorithms for a given point rotated by angle A2 can be obtained by substituting x for each occurrence of (h * cos A1) and by substituting y for each occurrence of (h * sin A1).

x' = (x * cos A2) - (y * sin A2)
y' = (x * sin A2) + (y * cos A2)


Shear

Some applications provide features that shear objects drawn in the client area. Applications that use shear capabilities use the SetWorldTransform function to set appropriate values in the world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM12 and eM21 members of XFORM specify the horizontal and vertical proportionality constants, respectively.

There are two components of the shear transformation. The first alters the vertical lines in an object; the second alters the horizontal lines. The following illustration shows a 20-by-20-unit rectangle sheared horizontally when copied from world space to page space.

A horizontal shear can be represented by the following algorithm:

x' = x + (Sx * y)

where x is the original x-coordinate, Sx is the proportionality constant, and x' is the result of the shear transformation.

A vertical shear can be represented by the following algorithm:

y' = y + (Sy * x)

where y is the original y-coordinate, Sy is the proportionality constant, and y' is the result of the shear transformation.

The horizontal-shear and vertical-shear transformations can be combined into a single operation using a 2-by-2 matrix.

|x' y'| == |x y| * |  1   Sx|
                   | Sy    1|

The 2-by-2 matrix that produced the shear contains the following values:

|1    1|
|0    1|


Reflection

Some applications provide features that reflect (or mirror) objects drawn in the client area. Applications that contain reflection capabilities use the SetWorldTransform function to set the appropriate values in the world-space to page-space transformation. This function receives a pointer to an XFORM structure containing the appropriate values. The eM11 and eM22 members of XFORM specify the horizontal and vertical reflection components, respectively.

The reflection transformation creates a mirror image of an object with respect to either the x- or y-axis. In short, reflection is just negative scaling. To produce a horizontal reflection, x-coordinates are multiplied by –1. To produce a vertical reflection, y-coordinates are multiplied by –1.

Horizontal reflection can be represented by the following algorithm:

x' = –x

where x is the x-coordinate and x' is the result of the reflection.

The 2-by-2 matrix that produced horizontal reflection contains the following values:

|-1    0|
|0     1|

Vertical reflection can be represented by the following algorithm:

y' = -y

where y is the y-coordinate and y' is the result of the reflection.

The 2-by-2 matrix that produced vertical reflection contains the following values:

|1    0|
|0   -1|

The horizontal-reflection and vertical-reflection operations can be combined into a single operation by using the following 2-by-2 matrix:

|-1    0|
|0    -1|


Combined World-to-Page Space Transformations

The five world-to-page transformations can be combined into a single 3-by-3 matrix. The CombineTransform function can be used to combine two world-space to page-space transformations. The combined transformations can be used to alter output associated with a particular device context (DC) by calling the SetWorldTransform function and supplying the elements for this matrix. When an application calls SetWorldTransform, it stores the elements of the 3-by-3 matrix in an XFORM structure. The members of this structure correspond to the first two columns of a 3-by-3 matrix; the last column of the matrix is not required because its values are constant.

The elements of the current world transformation matrix can be revived by calling the GetWorldTransform function and supplying a pointer to an XFORM structure.


Page-Space to Device-Space Transformations

The page-space to device-space transformation determines the mapping mode for all graphics output associated with a particular DC. A mapping mode is a scaling transformation that specifies the size of the units used for drawing operations. The mapping mode may also perform translation. In some cases, the mapping mode alters the orientation of the x- and y-axes in device space. The following topics describe the mapping modes.

  • Mapping Modes and Translations
  • Predefined Mapping Modes
  • Application-Defined Mapping Modes


Mapping Modes and Translations

The mapping modes are described in the following table.

Mapping mode | Description
MM_ANISOTROPIC | Each unit in page space is mapped to an application-specified unit in device space. The axis may or may not be equally scaled (for example, a circle drawn in world space may appear to be an ellipse when depicted on a given device). The orientation of the axis is also specified by the application.
MM_HIENGLISH | Each unit in page space is mapped to 0.001 inch in device space. The value of x increases from left to right. The value of y increases from bottom to top.
MM_HIMETRIC | Each unit in page space is mapped to 0.01 millimeter in device space. The value of x increases from left to right. The value of y increases from bottom to top.
MM_ISOTROPIC | Each unit in page space is mapped to an application-defined unit in device space. The axes are always equally scaled. The orientation of the axes may be specified by the application.
MM_LOENGLISH | Each unit in page space is mapped to 0.01 inch in device space. The value of x increases from left to right. The value of y increases from bottom to top.
MM_LOMETRIC | Each unit in page space is mapped to 0.1 millimeter in device space. The value of x increases from left to right. The value of y increases from bottom to top.
MM_TEXT | Each unit in page space is mapped to one pixel; that is, no scaling is performed at all. When no translation is in effect (this is the default), page space in the MM_TEXT mapping mode is equivalent to physical device space. The value of x increases from left to right. The value of y increases from top to bottom.
MM_TWIPS | Each unit in page space is mapped to one twentieth of a printer's point (1/1440 inch). The value of x increases from left to right. The value of y increases from bottom to top.

To set a mapping mode, call the SetMapMode function. Retrieve the current mapping mode for a DC by calling the GetMapMode function.

The page-space to device-space transformations consist of values calculated from the points given by the window and viewport. In this context, the window refers to the logical coordinate system of the page space, while the viewport refers to the device coordinate system of the device space. The window and viewport each consist of an origin, a horizontal ("x") extent, and a vertical ("y") extent). The window parameters are in logical coordinates; the viewport in device coordinates (pixels). The system combines the origins and extents from both the window and viewport to create the transformation. This means that the window and viewport each specify half of the factors needed to define the transformation used to map points in page space to device space. Thus, the system maps the window origin to the viewport origin and the window extents to the viewport extents, as shown in the following illustration.

The window and viewport extents establish a ratio or scaling factor used in the page-space to device-space transformations. For the six predefined mapping modes (MM_HIENGLISH, MM_LOENGLISH, MM_HIMETRIC, MM_LOMETRIC, MM_TEXT, and MM_TWIPS), the extents are set by the system when SetMapMode is called. They cannot be changed. The other two mapping modes (MM_ISOTROPIC and MM_ANISOTROPIC) require that the extents are specified. This is done by calling SetMapMode to set the appropriate mode and then calling the SetWindowExtEx and SetViewportExtEx functions to specify the extents. In the MM_ISOTROPIC mapping mode, it is important to call SetWindowExtEx before calling SetViewportExtEx.

The window and viewport origins establish the translation used in the page-space to device-space transformations. Set the window and viewport origins by using the SetWindowOrgEx and SetViewportOrgEx functions. The origins are independent of the extents, and an application can set them regardless of the current mapping mode. Changing a mapping mode does not affect the currently set origins (although it can affect the extents). Origins are specified in absolute units that the current mapping mode does not affect. To alter the origins, use the OffsetWindowOrgEx and OffsetViewportOrgEx functions.

The following formula shows the math involved in converting a point from page space to device space.

Dx = ((Lx - WOx) * VEx / WEx) + VOx

The following variables are involved.

Dx     x value in device units
Lx     x value in logical units (also known as page space units)
WOx     window x origin
VOx     viewport x origin
WEx     window x-extent
VEx     viewport x-extent

The same equation with y replacing x transforms the y component of a point.

The formula first offsets the point from its coordinate origin. This value, no longer biased by the origin, is then scaled into the destination coordinate system by the ratio of the extents. Finally, the scaled value is offset by the destination origin to its final mapping.

The LPtoDP and DPtoLP functions may be used to convert from logical points to device points and from device points to logical points, respectively.


Predefined Mapping Modes

Of the six predefined mapping modes, one is device dependent (MM_TEXT)—the remaining five (MM_HIENGLISH, MM_LOENGLISH, MM_HIMETRIC, MM_LOMETRIC, and MM_TWIPS) are device independent.

The default mapping mode is MM_TEXT. One logical unit equals one pixel. Positive x is to the right, and positive y is down. This mode maps directly to the device's coordinate system. The logical-to-physical mapping involves only an offset in x and y that is defined by the application-controlled window and viewport origins. The viewport and window extents are all set to 1, creating a one-to-one mapping.

Applications that display geometric shapes (circles, squares, polygons, and so on, make use of one of the device-independent mapping modes. For example, if you are writing an application to provide charting capabilities for a spreadsheet program and want to guarantee that the diameter of each pie chart is 2 inches, use the MM_LOENGLISH mapping mode and call the appropriate functions to draw and fill the chart. Specifying MM_LOENGLISH, guarantees that the diameter of the chart is consistent on any display or printer. If MM_TEXT is used instead of MM_LOENGLISH, a chart that appears circular on a VGA display would appear elliptical on an EGA display and would appear very small on a 300 dpi (dots per inch) laser printer.


Application-Defined Mapping Modes

The two application-defined mapping modes (MM_ISOTROPIC and MM_ANISOTROPIC) are provided for application-specific mapping modes. The MM_ISOTROPIC mode guarantees that logical units in the x-direction and in the y-direction are equal, while the MM_ANISOTROPIC mode allows the units to differ. A CAD or drawing application can benefit from the MM_ISOTROPIC mapping mode but may need to specify logical units that correspond to the increments on an engineer's scale (1/64 inch). These units would be difficult to obtain with the predefined mapping modes (MM_HIENGLISH or MM_HIMETRIC); however, they can easily be obtained by selecting the MM_ISOTROPIC (or MM_ANISOTROPIC) mode. The following example shows how to set logical units to 1/64 inch:

SetMapMode(hDC, MM_ISOTROPIC);
SetWindowExtEx(hDC, 64, 64, NULL);
SetViewportExtEx(hDC, GetDeviceCaps(hDC, LOGPIXELSX),
                      GetDeviceCaps(hDC, LOGPIXELSY), NULL);


Device-Space to Physical-Device Transformation

The device-space to physical-device transformation is unique in several respects. For example, it is limited to translation and is controlled by the system. The sole purpose of this transformation is to ensure that the origin of device space is mapped to the proper point on the physical device. There are no functions to set this transformation, nor are there any functions to retrieve related data.


Default Transformations

Whenever an application creates a DC and immediately begins calling GDI drawing or output functions, it takes advantage of the default page-space to device-space, and device-space to client-area transformations. A world-to-page space transformation cannot happen until the application first calls the SetGraphicsMode function to set the mode to GM_ADVANCED and then calls the SetWorldTransform function.

Use of MM_TEXT (the default page-space to device-space transformation) results in a one-to-one mapping; that is, a given point in page space maps to the same point in device space. As previously mentioned, this transformation is not specified by a matrix. Instead, it is obtained by dividing the width of the viewport by the width of the window and the height of the viewport by the height of the window. In the default case, the viewport dimensions are 1-pixel by 1-pixel and the window dimensions are 1-page unit by 1-page unit.

The device-space to physical-device (client area, desktop, or printer paper) transformation always results in a one-to-one mapping; that is, one unit in device space is always equivalent to one unit in the client area, on the desktop, or on a page. The sole purpose of this transformation is translation; it ensures that output appears correctly in an application's window no matter where that window is moved on the desktop.

The one unique aspect of MM_TEXT is the orientation of the y-axis in page space. In MM_TEXT, the positive y-axis extends downward and the negative y-axis extends upward.


Using Coordinate Spaces and Transformations

This section contains an example that demonstrates the following tasks:

  • Drawing graphics with predefined units.
  • Centering graphics in the application's client area.
  • Scaling graphics output to half its original size.
  • Translating graphics output 3/4 of an inch to the right.
  • Rotating graphics 30 degrees.
  • Shearing graphics output along the x-axis.
  • Reflecting graphics output about an imaginary horizontal axis drawn through its midpoint.

The following example was used to create the illustrations that appear earlier in this overview.

void TransformAndDraw(int iTransform, HWND hWnd)
{
    HDC hDC;
    XFORM xForm;
    RECT rect;

    // Retrieve a DC handle for the application's window.

    hDC = GetDC(hWnd);

    // Set the mapping mode to LOENGLISH. This moves the
    // client area origin from the upper left corner of the
    // window to the lower left corner (this also reorients
    // the y-axis so that drawing operations occur in a true
    // Cartesian space). It guarantees portability so that
    // the object drawn retains its dimensions on any display.

    SetGraphicsMode(hDC, GM_ADVANCED);
    SetMapMode(hDC, MM_LOENGLISH);

    // Set the appropriate world transformation (based on the
    // user's menu selection).

    switch (iTransform)
    {
        case SCALE:        // Scale to 1/2 of the original size.
            xForm.eM11 = (FLOAT) 0.5;
            xForm.eM12 = (FLOAT) 0.0;
            xForm.eM21 = (FLOAT) 0.0;
            xForm.eM22 = (FLOAT) 0.5;
            xForm.eDx  = (FLOAT) 0.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

        case TRANSLATE:   // Translate right by 3/4 inch.
            xForm.eM11 = (FLOAT) 1.0;
            xForm.eM12 = (FLOAT) 0.0;
            xForm.eM21 = (FLOAT) 0.0;
            xForm.eM22 = (FLOAT) 1.0;
            xForm.eDx  = (FLOAT) 75.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

        case ROTATE:      // Rotate 30 degrees counterclockwise.
            xForm.eM11 = (FLOAT) 0.8660;
            xForm.eM12 = (FLOAT) 0.5000;
            xForm.eM21 = (FLOAT) -0.5000;
            xForm.eM22 = (FLOAT) 0.8660;
            xForm.eDx  = (FLOAT) 0.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

        case SHEAR:       // Shear along the x-axis with a
                          // proportionality constant of 1.0.
            xForm.eM11 = (FLOAT) 1.0;
            xForm.eM12 = (FLOAT) 1.0;
            xForm.eM21 = (FLOAT) 0.0;
            xForm.eM22 = (FLOAT) 1.0;
            xForm.eDx  = (FLOAT) 0.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

        case REFLECT:     // Reflect about a horizontal axis.
            xForm.eM11 = (FLOAT) 1.0;
            xForm.eM12 = (FLOAT) 0.0;
            xForm.eM21 = (FLOAT) 0.0;
            xForm.eM22 = (FLOAT) -1.0;
            xForm.eDx  = (FLOAT) 0.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

        case NORMAL:      // Set the unity transformation.
            xForm.eM11 = (FLOAT) 1.0;
            xForm.eM12 = (FLOAT) 0.0;
            xForm.eM21 = (FLOAT) 0.0;
            xForm.eM22 = (FLOAT) 1.0;
            xForm.eDx  = (FLOAT) 0.0;
            xForm.eDy  = (FLOAT) 0.0;
            SetWorldTransform(hDC, &xForm);
            break;

    }

    // Find the midpoint of the client area.

    GetClientRect(hWnd, (LPRECT) &rect);
    DPtoLP(hDC, (LPPOINT) &rect, 2);

    // Select a hollow brush.

    SelectObject(hDC, GetStockObject(HOLLOW_BRUSH));

    // Draw the exterior circle.

    Ellipse(hDC, (rect.right / 2 - 100), (rect.bottom / 2 + 100),
        (rect.right / 2 + 100), (rect.bottom / 2 - 100));

    // Draw the interior circle.

    Ellipse(hDC, (rect.right / 2 -94), (rect.bottom / 2 + 94),
        (rect.right / 2 + 94), (rect.bottom / 2 - 94));

    // Draw the key.

    Rectangle(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 113),
        (rect.right / 2 + 13), (rect.bottom / 2 + 50));
    Rectangle(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 96),
        (rect.right / 2 + 13), (rect.bottom / 2 + 50));

    // Draw the horizontal lines.

    MoveToEx(hDC, (rect.right/2 - 150), (rect.bottom / 2 + 0), NULL);
    LineTo(hDC, (rect.right / 2 - 16), (rect.bottom / 2 + 0));

    MoveToEx(hDC, (rect.right / 2 - 13), (rect.bottom / 2 + 0), NULL);
    LineTo(hDC, (rect.right / 2 + 13), (rect.bottom / 2 + 0));

    MoveToEx(hDC, (rect.right / 2 + 16), (rect.bottom / 2 + 0), NULL);
    LineTo(hDC, (rect.right / 2 + 150), (rect.bottom / 2 + 0));

    // Draw the vertical lines.

    MoveToEx(hDC, (rect.right/2 + 0), (rect.bottom / 2 - 150), NULL);
    LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 - 16));

    MoveToEx(hDC, (rect.right / 2 + 0), (rect.bottom / 2 - 13), NULL);
    LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 13));

    MoveToEx(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 16), NULL);
    LineTo(hDC, (rect.right / 2 + 0), (rect.bottom / 2 + 150));

    ReleaseDC(hWnd, hDC);
}


Coordinate Space and Transformation Reference

The following elements are used with coordinate spaces and transformations.

  • Coordinate Space and Transformation Functions
  • Coordinate Space and Transformation Structures


Coordinate Space and Transformation Functions

The following functions are used with coordinate spaces and transformations.

Function | Description
ClientToScreen | Converts the client-area coordinates of a specified point to screen coordinates.
CombineTransform | Concatenates two world-space to page-space transformations.
DPtoLP | Converts device coordinates into logical coordinates.
GetCurrentPositionEx | Retrieves the current position in logical coordinates.
GetGraphicsMode | Retrieves the current graphics mode for the specified device context.
GetMapMode | Retrieves the current mapping mode.
GetViewportExtEx | Retrieves the x-extent and y-extent of the current viewport for the specified device context.
GetViewportOrgEx | Retrieves the x-coordinates and y-coordinates of the viewport origin for the specified device context.
GetWindowExtEx | Retrieves the x-extent and y-extent of the window for the specified device context.
GetWindowOrgEx | Retrieves the x-coordinates and y-coordinates of the window origin for the specified device context.
GetWorldTransform | Retrieves the current world-space to page-space transformation.
LPtoDP | Converts logical coordinates into device coordinates.
MapWindowPoints | Converts (maps) a set of points from a coordinate space relative to one window to a coordinate space relative to another window.
ModifyWorldTransform | Changes the world transformation for a device context using the specified mode.
OffsetViewportOrgEx | Modifies the viewport origin for a device context using the specified horizontal and vertical offsets.
OffsetWindowOrgEx | Modifies the window origin for a device context using the specified horizontal and vertical offsets.
ScaleViewportExtEx | Modifies the viewport for a device context using the ratios formed by the specified multiplicands and divisors.
ScaleWindowExtEx | Modifies the window for a device context using the ratios formed by the specified multiplicands and divisors.
ScreenToClient | Converts the screen coordinates of a specified point on the screen to client coordinates.
SetGraphicsMode | Sets the graphics mode for the specified device context.
SetMapMode | Sets the mapping mode of the specified device context.
SetViewportExtEx | Sets the horizontal and vertical extents of the viewport for a device context by using the specified values.
SetViewportOrgEx | Specifies which device point maps to the window origin (0,0).
SetWindowExtEx | Sets the horizontal and vertical extents of the window for a device context by using the specified values.
SetWindowOrgEx | Specifies which window point maps to the viewport origin (0,0).
SetWorldTransform | Sets a two-dimensional linear transformation between world space and page space for the specified device context.


ClientToScreen

The ClientToScreen function converts the client-area coordinates of a specified point to screen coordinates.

BOOL ClientToScreen(
  HWND hWnd,       // handle to window
  LPPOINT lpPoint  // screen coordinates
);

Parameters

hWnd
[in] Handle to the window whose client area is used for the conversion.
lpPoint
[in/out] Pointer to a POINT structure that contains the client coordinates to be converted. The new screen coordinates are copied into this structure if the function succeeds.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The ClientToScreen function replaces the client-area coordinates in the POINT structure with the screen coordinates. The screen coordinates are relative to the upper-left corner of the screen. Note, a screen-coordinate point that is above the window's client area has a negative y-coordinate. Similarly, a screen coordinate to the left of a client area has a negative x-coordinate.

All coordinates are device coordinates.

For an example, see Drawing Lines with the Mouse.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, MapWindowPoints, POINT, ScreenToClient


CombineTransform

The CombineTransform function concatenates two world-space to page-space transformations.

BOOL CombineTransform(
  LPXFORM lpxformResult,  // combined transformation
  CONST XFORM *lpxform1,  // first transformation
  CONST XFORM *lpxform2   // second transformation
);

Parameters

lpxformResult
[out] Pointer to an XFORM structure that receives the combined transformation.
lpxform1
[in] Pointer to an XFORM structure that specifies the first transformation.
lpxform2
[in] Pointer to an XFORM structure that specifies the second transformation.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Applying the combined transformation has the same effect as applying the first transformation and then applying the second transformation.

The three transformations need not be distinct. For example, lpxform1 can point to the same XFORM structure as lpxformResult.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWorldTransform, ModifyWorldTransform, SetWorldTransform, XFORM


DPtoLP

The DPtoLP function converts device coordinates into logical coordinates. The conversion depends on the mapping mode of the device context, the settings of the origins and extents for the window and viewport, and the world transformation.

BOOL DPtoLP(
  HDC hdc,           // handle to device context
  LPPOINT lpPoints,  // array of points
  int nCount         // count of points in array
);

Parameters

hdc
[in] Handle to the device context.
lpPoints
[in/out] Pointer to an array of POINT structures. The x- and y-coordinates contained in each POINT structure will be transformed.
nCount
[in] Specifies the number of points in the array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The DPtoLP function fails if the device coordinates exceed 27 bits, or if the converted logical coordinates exceed 32 bits. In the case of such an overflow, the results for all the points are undefined.

For an example, see Using Coordinate Spaces and Transformations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, LPtoDP, POINT


GetCurrentPositionEx

The GetCurrentPositionEx function retrieves the current position in logical coordinates.

BOOL GetCurrentPositionEx(
  HDC hdc,        // handle to device context
  LPPOINT lpPoint // current position
);

Parameters

hdc
[in] Handle to the device context.
lpPoint
[out] Pointer to a POINT structure that receives the coordinates of the current position.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, MoveToEx, POINT


GetGraphicsMode

The GetGraphicsMode function retrieves the current graphics mode for the specified device context.

int GetGraphicsMode(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the current graphics mode. It can be one of the following values.

Value | Meaning
GM_COMPATIBLE | The current graphics mode is the compatible graphics mode, a mode that is compatible with 16-bit Windows. In this graphics mode, an application cannot set or modify the world transformation for the specified device context. The compatible graphics mode is the default graphics mode.
GM_ADVANCED | Windows NT/2000 or later: The current graphics mode is the advanced graphics mode, a mode that allows world transformations. In this graphics mode, an application can set or modify the world transformation for the specified device context. Windows 95/98/Me: The GM_ADVANCED value is not supported.

Otherwise, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can set the graphics mode for a device context by calling the SetGraphicsMode function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, SetGraphicsMode


GetMapMode

The GetMapMode function retrieves the current mapping mode.

int GetMapMode(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value specifies the mapping mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The following are the various mapping modes.

Mode | Description
MM_ANISOTROPIC | Logical units are mapped to arbitrary units with arbitrarily scaled axes. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units, orientation, and scaling requiredt.
MM_HIENGLISH | Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up.
MM_HIMETRIC | Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up.
MM_ISOTROPIC | Logical units are mapped to arbitrary units with equally scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units and the orientation of the axes. Graphics device interface makes adjustments as necessary to ensure the x and y units remain the same size. (When the windows extent is set, the viewport will be adjusted to keep the units isotropic).
MM_LOENGLISH | Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up.
MM_LOMETRIC | Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up.
MM_TEXT | Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down.
MM_TWIPS | Each logical unit is mapped to one twentieth of a printer's point (1/1440 inch, also called a "twip"). Positive x is to the right; positive y is up.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, SetMapMode, SetWindowExtEx, SetViewportExtEx


GetViewportExtEx

The GetViewportExtEx function retrieves the x-extent and y-extent of the current viewport for the specified device context.

BOOL GetViewportExtEx(
  HDC hdc,      // handle to device context
  LPSIZE lpSize // viewport dimensions
);

Parameters

hdc
[in] Handle to the device context.
lpSize
[out] Pointer to a SIZE structure that receives the x- and y-extents, in device units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWindowExtEx, SetViewportExtEx, SetWindowExtEx


GetViewportOrgEx

The GetViewportOrgEx function retrieves the x-coordinates and y-coordinates of the viewport origin for the specified device context.

BOOL GetViewportOrgEx(
  HDC hdc,        // handle to device context
  LPPOINT lpPoint // viewport origin
);

Parameters

hdc
[in] Handle to the device context.
lpPoint
[out] Pointer to a POINT structure that receives the coordinates of the origin, in device units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWindowOrgEx, POINT, SetViewportOrgEx, SetWindowOrgEx


GetWindowExtEx

This function retrieves the x-extent and y-extent of the window for the specified device context.

BOOL GetWindowExtEx(
  HDC hdc,        // handle to device context
  LPSIZE lpSize   // window extents
);

Parameters

hdc
[in] Handle to the device context.
lpSize
[out] Pointer to a SIZE structure that receives the x- and y-extents in page-space units, that is, logical units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportExtEx, SetViewportExtEx, SetWindowExtEx


GetWindowOrgEx

The GetWindowOrgEx function retrieves the x-coordinates and y-coordinates of the window origin for the specified device context.

BOOL GetWindowOrgEx(
  HDC hdc,         // handle to device context
  LPPOINT lpPoint  // window origin
);

Parameters

hdc
[in] Handle to the device context.
lpPoint
[out] Pointer to a POINT structure that receives the coordinates, in logical units, of the window origin.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportOrgEx, SetViewportOrgEx, SetWindowOrgEx


GetWorldTransform

The GetWorldTransform function retrieves the current world-space to page-space transformation.

BOOL GetWorldTransform(
  HDC hdc,         // handle to device context
  LPXFORM lpXform  // transformation
);

Parameters

hdc
[in] Handle to the device context.
lpXform
[out] Pointer to an XFORM structure that receives the current world-space to page-space transformation.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The precision of the transformation may be altered if an application calls the ModifyWorldTransform function prior to calling GetWorldTransform. (This is because the internal format for storing transformation values uses a higher precision than a FLOAT value.)

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, ModifyWorldTransform, SetWorldTransform


LPtoDP

The LPtoDP function converts logical coordinates into device coordinates. The conversion depends on the mapping mode of the device context, the settings of the origins and extents for the window and viewport, and the world transformation.

BOOL LPtoDP(
  HDC hdc,           // handle to device context
  LPPOINT lpPoints,  // array of points
  int nCount         // count of points in array
);

Parameters

hdc
[in] Handle to the device context.
lpPoints
[in/out] Pointer to an array of POINT structures. The x-coordinates and y-coordinates contained in each of the POINT structures will be transformed.
nCount
[in] Specifies the number of points in the array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This function fails if the logical coordinates exceed 32 bits, or if the converted device coordinates exceed 27 bits. In the case of such an overflow, the results for all the points are undefined.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, DPtoLP, POINT


MapWindowPoints

The MapWindowPoints function converts (maps) a set of points from a coordinate space relative to one window to a coordinate space relative to another window.

int MapWindowPoints(
  HWND hWndFrom,     // handle to source window
  HWND hWndTo,       // handle to destination window
  LPPOINT lpPoints,  // array of points to map
  UINT cPoints       // number of points in array
);

Parameters

hWndFrom
[in] Handle to the window from which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are presumed to be in screen coordinates.
hWndTo
[in] Handle to the window to which points are converted. If this parameter is NULL or HWND_DESKTOP, the points are converted to screen coordinates.
lpPoints
[in/out] Pointer to an array of POINT structures that contain the set of points to be converted. The points are in device units. This parameter can also point to a RECT structure, in which case the cPoints parameter should be set to 2.
cPoints
[in] Specifies the number of POINT structures in the array pointed to by the lpPoints parameter.

Return Values

If the function succeeds, the low-order word of the return value is the number of pixels added to the horizontal coordinate of each source point in order to compute the horizontal coordinate of each destination point; the high-order word is the number of pixels added to the vertical coordinate of each source point in order to compute the vertical coordinate of each destination point.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If hWndFrom or hWndTo (or both) are mirrored windows (that is, have WS_EX_LAYOUTRTL extended style), MapWindowPoints will automatically adjust mirrored coordinates if you pass two or less points in lpPoints. If you pass more than two points, the function will not fail but it will return erroneous positions. Thus, to guarantee the correct transformation of rectangle coordinates, you must call MapWindowPoints with two or less points at a time, as shown in the following example:

    RECT        rc[10];

   for(int i =0; i < (sizeof(rc)/sizeof(rc[0])); i++)
   {
       MapWindowPoints(hWnd1, hWnd2, (LPPOINT)(&rc[i]), (sizeof(RECT)/sizeof(POINT)) );
   }

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, ClientToScreen, POINT, RECT, ScreenToClient


ModifyWorldTransform

The ModifyWorldTransform function changes the world transformation for a device context using the specified mode.

BOOL ModifyWorldTransform(
  HDC hdc,               // handle to device context
  CONST XFORM *lpXform,  // transformation data
  DWORD iMode            // modification mode
);

Parameters

hdc
[in] Handle to the device context.
lpXform
[in] Pointer to an XFORM structure used to modify the world transformation for the given device context.
iMode
[in] Specifies how the transformation data modifies the current world transformation. This parameter must be one of the following values.
Value | Description
MWT_IDENTITY | Resets the current world transformation by using the identity matrix. If this mode is specified, the XFORM structure pointed to by lpXform is ignored.
MWT_LEFTMULTIPLY | Multiplies the current transformation by the data in the XFORM structure. (The data in the XFORM structure becomes the left multiplicand, and the data for the current transformation becomes the right multiplicand.)
MWT_RIGHTMULTIPLY | Multiplies the current transformation by the data in the XFORM structure. (The data in the XFORM structure becomes the right multiplicand, and the data for the current transformation becomes the left multiplicand.)

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The ModifyWorldTransform function will fail unless graphics mode for the specified device context has been set to GM_ADVANCED by previously calling the SetGraphicsMode function. Likewise, it will not be possible to reset the graphics mode for the device context to the default GM_COMPATIBLE mode, unless world transform has first been reset to the default identity transform by calling SetWorldTransform or ModifyWorldTransform.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWorldTransform, SetWorldTransform, SetGraphicsMode, XFORM


OffsetViewportOrgEx

The OffsetViewportOrgEx function modifies the viewport origin for a device context using the specified horizontal and vertical offsets.

BOOL OffsetViewportOrgEx(
  HDC hdc,         // handle to device context
  int nXOffset,    // horizontal offset
  int nYOffset,    // vertical offset
  LPPOINT lpPoint  // original origin
);

Parameters

hdc
[in] Handle to the device context.
nXOffset
[in] Specifies the horizontal offset, in device units.
nYOffset
[in] Specifies the vertical offset, in device units.
lpPoint
[out] Pointer to a POINT structure. The previous viewport origin, in device units, is placed in this structure. If lpPoint is NULL, the previous viewport origin is not returned.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

The new origin is the sum of the current origin and the horizontal and vertical offsets.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportOrgEx, OffsetWindowOrgEx, SetViewportOrgEx


OffsetWindowOrgEx

The OffsetWindowOrgEx function modifies the window origin for a device context using the specified horizontal and vertical offsets.

BOOL OffsetWindowOrgEx(
  HDC hdc,          // handle to device context
  int nXOffset,     // horizontal offset
  int nYOffset,     // vertical offset
  LPPOINT lpPoint   // original origin
);

Parameters

hdc
[in] Handle to the device context.
nXOffset
[in] Specifies the horizontal offset, in logical units.
nYOffset
[in] Specifies the vertical offset, in logical units.
lpPoint
[out] Pointer to a POINT structure. The logical coordinates of the previous window origin are placed in this structure. If lpPoint is NULL, the previous origin is not returned.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportOrgEx, OffsetViewportOrgEx, POINT


ScaleViewportExtEx

The ScaleViewportExtEx function modifies the viewport for a device context using the ratios formed by the specified multiplicands and divisors.

BOOL ScaleViewportExtEx(
  HDC hdc,        // handle to device context
  int Xnum,       // horizontal multiplicand
  int Xdenom,     // horizontal divisor
  int Ynum,       // vertical multiplicand
  int Ydenom,     // vertical divisor
  LPSIZE lpSize   // previous viewport extents
);

Parameters

hdc
[in] Handle to the device context.
Xnum
[in] Specifies the amount by which to multiply the current horizontal extent.
Xdenom
[in] Specifies the amount by which to divide the current horizontal extent.
Ynum
[in] Specifies the amount by which to multiply the current vertical extent.
Ydenom
[in] Specifies the amount by which to divide the current vertical extent.
lpSize
[out] Pointer to a SIZE structure that receives the previous viewport extents, in device units. If lpSize is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The viewport extents are modified as follows:

    xNewVE = (xOldVE * Xnum) / Xdenom
    yNewVE = (yOldVE * Ynum) / Ydenom

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportExtEx, SIZE


ScaleWindowExtEx

The ScaleWindowExtEx function modifies the window for a device context using the ratios formed by the specified multiplicands and divisors.

BOOL ScaleWindowExtEx(
  HDC hdc,        // handle to device context
  int Xnum,       // horizontal multiplicand
  int Xdenom,     // horizontal divisor
  int Ynum,       // vertical multiplicand
  int Ydenom,     // vertical divisor
  LPSIZE lpSize   // previous window extents
);

Parameters

hdc
[in] Handle to the device context.
Xnum
[in] Specifies the amount by which to multiply the current horizontal extent.
Xdenom
[in] Specifies the amount by which to divide the current horizontal extent.
Ynum
[in] Specifies the amount by which to multiply the current vertical extent.
Ydenom
[in] Specifies the amount by which to divide the current vertical extent.
lpSize
[out] Pointer to a SIZE structure that receives the previous window extents, in logical units. If lpSize is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The window extents are modified as follows:

    xNewWE = (xOldWE * Xnum) / Xdenom
    yNewWE = (yOldWE * Ynum) / Ydenom

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWindowExtEx, SIZE


ScreenToClient

The ScreenToClient function converts the screen coordinates of a specified point on the screen to client coordinates.

BOOL ScreenToClient(
  HWND hWnd,        // handle to window
  LPPOINT lpPoint   // screen coordinates
);

Parameters

hWnd
[in] Handle to the window whose client area will be used for the conversion.
lpPoint
[in] Pointer to a POINT structure that specifies the screen coordinates to be converted.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The function uses the window identified by the hWnd parameter and the screen coordinates given in the POINT structure to compute client coordinates. It then replaces the screen coordinates with the client coordinates. The new coordinates are relative to the upper-left corner of the specified window's client area.

The ScreenToClient function assumes the specified point is in screen coordinates.

All coordinates are in device units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, ClientToScreen, MapWindowPoints, POINT


SetGraphicsMode

The SetGraphicsMode function sets the graphics mode for the specified device context.

int SetGraphicsMode(
  HDC hdc,    // handle to device context
  int iMode   // graphics mode
);

Parameters

hdc
[in] Handle to the device context.
iMode
[in] Specifies the graphics mode. This parameter can be one of the following values.
Value | Meaning
GM_COMPATIBLE | Sets the graphics mode that is compatible with 16-bit Windows. This is the default mode. If this value is specified, the application can only modify the world-to-device transform by calling functions that set window and viewport extents and origins, but not by using SetWorldTransform or ModifyWorldTransform; calls to those functions will fail. Examples of functions that set window and viewport extents and origins are SetViewportExtEx and SetWindowExtEx.
GM_ADVANCED Windows NT/ 2000: Sets the advanced graphics mode that allows world transformations. This value must be specified if the application will set or modify the world transformation for the specified device context. In this mode all graphics, including text output, fully conform to the world-to-device transformation specified in the device context.

Windows 95/98 :The GM_ADVANCED value is not supported. When playing enhanced metafiles, Windows 95/98 attempts to make enhanced metafiles on Windows 95/98 look the same as they do on Windows NT/Windows 2000. To accomplish this, Windows 95/98 may simulate GM_ADVANCED mode when playing specific enhanced metafile records.

Return Values

If the function succeeds, the return value is the old graphics mode.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

There are three areas in which graphics output differs according to the graphics mode:

  1. Text Output: In the GM_COMPATIBLE mode, TrueType (or vector font) text output behaves much the same way as raster font text output with respect to the world-to-device transformations in the DC. The TrueType text is always written from left to right and right side up, even if the rest of the graphics will be flipped on the x or y axis. Only the height of the TrueType (or vector font) text is scaled. The only way to write text that is not horizontal in the GM_COMPATIBLE mode is to specify nonzero escapement and orientation for the logical font selected in this device context.

    In the GM_ADVANCED mode, TrueType (or vector font) text output fully conforms to the world-to-device transformation in the device context. The raster fonts only have very limited transformation capabilities (stretching by some integer factors). Graphics device interface (GDI) tries to produce the best output it can with raster fonts for nontrivial transformations.

  2. Rectangle Exclusion: If the default GM_COMPATIBLE graphics mode is set, the system excludes bottom and rightmost edges when it draws rectangles.

    The GM_ADVANCED graphics mode is required if applications want to draw rectangles that are bottom-right inclusive.

  3. Arc Drawing: If the default GM_COMPATIBLE graphics mode is set, GDI draws arcs using the current arc direction in the device space. With this convention, arcs do not respect page-to-device transforms that require a flip along the x or y axis.

    If the GM_ADVANCED graphics mode is set, GDI always draws arcs in the counterclockwise direction in logical space. This is equivalent to the statement that, in the GM_ADVANCED graphics mode, both arc control points and arcs themselves fully respect the device context's world-to-device transformation.

For an example, see Using Coordinate Spaces and Transformations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, CreateDC, GetArcDirection, GetDC, GetGraphicsMode, ModifyWorldTransform, SetArcDirection, SetViewportExtent, SetViewportExtEx, SetWindowExtent, SetWindowExtEx, SetWorldTransform


SetMapMode

The SetMapMode function sets the mapping mode of the specified device context. The mapping mode defines the unit of measure used to transform page-space units into device-space units, and also defines the orientation of the device's x and y axes.

int SetMapMode(
  HDC hdc,        // handle to device context
  int fnMapMode   // new mapping mode
);

Parameters

hdc
[in] Handle to the device context.
fnMapMode
[in] Specifies the new mapping mode. This parameter can be one of the following values.
Value | Description
MM_ANISOTROPIC | Logical units are mapped to arbitrary units with arbitrarily scaled axes. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units, orientation, and scaling.
MM_HIENGLISH | Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up.
MM_HIMETRIC | Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up.
MM_ISOTROPIC | Logical units are mapped to arbitrary units with equally scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. Use the SetWindowExtEx and SetViewportExtEx functions to specify the units and the orientation of the axes. Graphics device interface (GDI) makes adjustments as necessary to ensure the x and y units remain the same size (When the window extent is set, the viewport will be adjusted to keep the units isotropic).
MM_LOENGLISH | Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up.
MM_LOMETRIC | Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up.
MM_TEXT | Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down.
MM_TWIPS | Each logical unit is mapped to one twentieth of a printer's point (1/1440 inch, also called a twip). Positive x is to the right; positive y is up.

Return Values

If the function succeeds, the return value identifies the previous mapping mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The MM_TEXT mode allows applications to work in device pixels, whose size varies from device to device.

The MM_HIENGLISH, MM_HIMETRIC, MM_LOENGLISH, MM_LOMETRIC, and MM_TWIPS modes are useful for applications drawing in physically meaningful units (such as inches or millimeters).

The MM_ISOTROPIC mode ensures a 1:1 aspect ratio.

The MM_ANISOTROPIC mode allows the x-coordinates and y-coordinates to be adjusted independently.

For an example, see Using Coordinate Spaces and Transformations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetMapMode, SetViewportExtEx, SetViewportOrgEx, SetWindowExtEx, SetWindowOrgEx


SetViewportExtEx

The SetViewportExtEx function sets the horizontal and vertical extents of the viewport for a device context by using the specified values.

BOOL SetViewportExtEx(
  HDC hdc,       // handle to device context
  int nXExtent,  // new horizontal viewport extent
  int nYExtent,  // new vertical viewport extent
  LPSIZE lpSize  // original viewport extent
);

Parameters

hdc
[in] Handle to the device context.
nXExtent
[in] Specifies the horizontal extent, in device units, of the viewport.
nYExtent
[in] Specifies the vertical extent, in device units, of the viewport.
lpSize
[out] Pointer to a SIZE structure that receives the previous viewport extents, in device units. If lpSize is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The viewport refers to the device coordinate system of the device space. The extent is the maximum value of an axis. This function sets the maximum values for the horizontal and vertical axes of the viewport in device coordinates (or pixels). When mapping between page space and device space, SetWindowExtEx and SetViewportExtEx determine the scaling factor between the window and the viewport. For more information, see Transformation of Coordinate Spaces.

When the following mapping modes are set, calls to the SetWindowExtEx and SetViewportExtEx 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 SetWindowExtEx function before it calls SetViewportExtEx. Note that for the MM_ISOTROPIC mode certain portions of a nonsquare screen may not be available for display because the logical units on both axes represent equal physical distances.

For an example, see Invalidating the Client Area.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportExtEx, SetWindowExtEx, SIZE


SetViewportOrgEx

The SetViewportOrgEx function specifies which device point maps to the window origin (0,0).

BOOL SetViewportOrgEx(
  HDC hdc,        // handle to device context
  int X,          // new x-coordinate of viewport origin
  int Y,          // new y-coordinate of viewport origin
  LPPOINT lpPoint // original viewport origin
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the x-coordinate, in device units, of the new viewport origin.
Y
[in] Specifies the y-coordinate, in device units, of the new viewport origin.
lpPoint
[out] Pointer to a POINT structure that receives the previous viewport origin, in device coordinates. If lpPoint is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This function (along with SetViewportExtEx and SetWindowExtEx) helps define the mapping from the logical coordinate space (also known as a window) to the device coordinate space (the viewport). SetViewportOrgEx specifies which device point maps to the logical point (0,0). It has the effect of shifting the axes so that the logical point (0,0) no longer refers to the upper-left corner.

//map the logical point (0,0) to the device point (xViewOrg, yViewOrg)
SetViewportOrgEx ( hdc, xViewOrg, yViewOrg, NULL)

This is related to the SetViewportOrgEx function. Generally, you will use one function or the other, but not both. Regardless of your use of SetWindowOrgEx and SetViewportOrgEx, the device point (0,0) is always the upper-left corner.

For an example, see Redrawing in the Update Region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportOrgEx, POINT, SetWindowOrgEx


SetWindowExtEx

The SetWindowExtEx function sets the horizontal and vertical extents of the window for a device context by using the specified values.

BOOL SetWindowExtEx(
  HDC hdc,       // handle to device context
  int nXExtent,  // new horizontal window extent
  int nYExtent,  // new vertical window extent
  LPSIZE lpSize  // original window extent
);

Parameters

hdc
[in] Handle to the device context.
nXExtent
[in] Specifies the window's horizontal extent in logical units.
nYExtent
[in] Specifies the window's vertical extent in logical units.
lpSize
[out] Pointer to a SIZE structure that receives the previous window extents, in logical units. If lpSize is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The window refers to the logical coordinate system of the page space. The extent is the maximum value of an axis. This function sets the maximum values for the horizontal and vertical axes of the window (in logical coordinates). When mapping between page space and device space, SetViewportExtEx and SetWindowExtEx determine the scaling factor between the window and the viewport. For more information, see Transformation of Coordinate Spaces.

When the following mapping modes are set, calls to the SetWindowExtEx and SetViewportExtEx 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 SetWindowExtEx function before calling SetViewportExtEx. Note that for the MM_ISOTROPIC mode, certain portions of a nonsquare screen may not be available for display because the logical units on both axes represent equal physical distances.

For an example, see Invalidating the Client Area.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWindowExtEx, SetViewportExtEx, SIZE


SetWindowOrgEx

The SetWindowOrgEx function specifies which window point maps to the viewport origin (0,0).

BOOL SetWindowOrgEx(
  HDC hdc,        // handle to device context
  int X,          // new x-coordinate of window origin
  int Y,          // new y-coordinate of window origin
  LPPOINT lpPoint // original window origin
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the logical x-coordinate of the new window origin.
Y
[in] Specifies the logical y-coordinate of the new window origin.
lpPoint
[out] Pointer to a POINT structure that receives the previous origin of the window. If lpPoint is NULL, this parameter is not used.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This helps define the mapping from the logical coordinate space (also known as a window) to the device coordinate space (the viewport). SetWindowOrgEx specifies which logical point maps to the device point (0,0). It has the effect of shifting the axes so that the logical point (0,0) no longer refers to the upper-left corner.

//map the logical point (xWinOrg, yWinOrg) to the device point (0,0)
SetWindowOrgEx (hdc, xWinOrg, yWinOrg, NULL)

This is related to the SetViewportOrgEx function. Generally, you will use one function or the other, but not both. Regardless of your use of SetWindowOrgEx and SetViewportOrgEx, the device point (0,0) is always the upper-left corner.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetViewportOrgEx, GetWindowOrgEx, POINT, SetViewportOrgEx


SetWorldTransform

The SetWorldTransform function 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(
  HDC hdc,               // handle to device context
  CONST XFORM *lpXform   // transformation data
);

Parameters

hdc
[in] Handle to the device context.
lpXform
[in] Pointer to an XFORM structure that contains the transformation data.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

For any coordinates (x, y) in world space, the transformed coordinates in page space (x', y') can be determined by the following algorithm:

x' = x * eM11 + y * eM21 + eDx,
y' = x * eM12 + y * eM22 + eDy,

where the transformation matrix is represented by the following:

| eM11 eM12 0 |
| eM21 eM22 0 |
| eDx  eDy  1 |

This function uses logical units.

The world transformation is usually used to scale or rotate logical images in a device-independent way.

The default world transformation is the identity matrix with zero offset.

The SetWorldTransform function will fail unless the graphics mode for the given device context has been set to GM_ADVANCED by previously calling the SetGraphicsMode function. Likewise, it will not be possible to reset the graphics mode for the device context to the default GM_COMPATIBLE mode, unless the world transformation has first been reset to the default identity transformation by calling SetWorldTransform or ModifyWorldTransform.

For an example, see Using Coordinate Spaces and Transformations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Functions, GetWorldTransform, ModifyWorldTransform, SetGraphicsMode, SetMapMode, SetViewportExtEx, SetViewportOrgEx, SetWindowExtEx, SetWindowOrgEx, XFORM


Coordinate Space and Transformation Structures

The following structure is used with coordinate spaces and transformations.

XFORM


XFORM

The XFORM structure specifies a world-space to page-space transformation.

typedef struct  _XFORM {
  FLOAT eM11;
  FLOAT eM12;
  FLOAT eM21;
  FLOAT eM22;
  FLOAT eDx;
  FLOAT eDy;
} XFORM, *PXFORM;

Members

eM11
Specifies the following.
Operation | Meaning
Scaling | Horizontal scaling component
Rotation | Cosine of rotation angle
Reflection | Horizontal component

eM12
Specifies the following.
Operation | Meaning
Shear | Horizontal proportionality constant
Rotation | Sine of the rotation angle

eM21
Specifies the following.
Operation | Meaning
Shear | Vertical proportionality constant
Rotation | Negative sine of the rotation angle

eM22
Specifies the following.
Operation | Meaning
Scaling | Vertical scaling component
Rotation | Cosine of rotation angle
Reflection | Vertical reflection component

eDx
Specifies the horizontal translation component, in logical units.
eDy
Specifies the vertical translation component, in logical units.

Remarks

The following list describes how the members are used for each operation.

Operation | eM11 | eM12 | eM21 | eM22
Rotation | Cosine | Sine | Negative sine | Cosine
Scaling | Horizontal scaling component | Not used | Not used | Vertical Scaling Component
Shear | Not used | Horizontal Proportionality Constant | Vertical Proportionality Constant | Not used
Reflection | Horizontal Reflection Component | Not used | Not used | Vertical Reflection Component

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Coordinate Spaces and Transformations Overview, Coordinate Space and Transformation Structures, ExtCreateRegion, GetWorldTransform, ModifyWorldTransform, PlayEnhMetaFile, SetWorldTransform


Device Contexts

A device context is a structure that defines a set of graphic objects and their associated attributes, as well as the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for painting and filling, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations, and a path for painting and drawing operations. The remainder of this section is divided into the following three areas.

  • About Device Contexts
  • Using the Device Context Functions
  • Device Context Reference


About Device Contexts

Device independence is one of the chief features of Microsoft® Windows®. Win32®-based applications can draw and print output on a variety of devices. The software that supports this device independence is contained in two dynamic-link libraries. The first, Gdi.dll, is referred to as the graphics device interface (GDI); the second is referred to as a device driver. The name of the second depends on the device where the application draws output. For example, if the application draws output in the client area of its window on a VGA display, this library is Vga.dll; if the application prints output on an Epson FX-80 printer, this library is Epson9.dll.

An application must inform GDI to load a particular device driver and, once the driver is loaded, to prepare the device for drawing operations (such as selecting a line color and width, a brush pattern and color, a font typeface, a clipping region, and so on). These tasks are accomplished by creating and maintaining a device context (DC). A DC is a structure that defines a set of graphic objects and their associated attributes, and the graphic modes that affect output. The graphic objects include a pen for line drawing, a brush for painting and filling, a bitmap for copying or scrolling parts of the screen, a palette for defining the set of available colors, a region for clipping and other operations, and a path for painting and drawing operations. Unlike most of the structures, an application never has direct access to the DC; instead, it operates on the structure indirectly by calling various functions.

This overview provides information on the following topics:

• Graphic Objects

• Device Context Types

• Device Context Operations

• ICM-Enabled Device Context Functions


Graphic Objects

The pen, brush, bitmap, palette, region, and path associated with a DC are referred to as its graphic objects. The following attributes are associated with each of these objects.

Graphic object | Associated attributes
Bitmap | Size, in bytes; dimensions, in pixels; color-format; compression scheme; and so on.
Brush | Style, color, pattern, and origin.
Palette | Colors and size (or number of colors).
Font | Typeface name, width, height, weight, character set, and so on.
Path | Shape.
Pen | Style, width, and color.
Region | Location and dimensions.

When an application creates a DC, the system automatically stores a set of default objects in it. (There is no default bitmap or path.) An application can examine the attributes of the default objects by calling the GetCurrentObject and GetObject functions. The application can change these defaults by creating a new object and selecting it into the DC. An object is selected into a DC by calling the SelectObject function.

An application can set the current brush color to a specified color value with SetDCBrushColor .

The GetDCBrushColor function returns the DC brush color. The SetDCPenColor function sets the pen color to a specified color value. The GetDCPenColor function returns the DC pen color.


Graphic Modes

The Win32 API supports five graphic modes that allow an application to specify how colors are mixed, where output appears, how the output is scaled, and so on. These modes, which are stored in a DC, are described in the following table.

Graphics mode | Description
Background | Defines how background colors are mixed with existing window or screen colors for bitmap and text operations.
Drawing | Defines how foreground colors are mixed with existing window or screen colors for pen, brush, bitmap, and text operations.
Mapping | Defines how graphics output is mapped from logical (or world) space onto the window, screen, or printer paper.
Polygon-fill | Defines how the brush pattern is used to fill the interior of complex regions.
Stretching | Defines how bitmap colors are mixed with existing window or screen colors when the bitmap is compressed (or scaled down).

As it does with graphic objects, the system initializes a DC with default graphic modes. An application can retrieve and examine these default modes by calling the following functions.

Graphics mode | Function
Background | GetBkMode
Drawing | GetROP2
Mapping | GetMapMode
Polygon-fill | GetPolyFillMode
Stretching | GetStretchBltMode

An application can change the default modes by calling one of the following functions.

Graphics mode | Function
Background | SetBkMode
Drawing | SetROP2
Mapping | SetMapMode
Polygon-fill | SetPolyFillMode
Stretching | SetStretchBltMode


Device Context Types

There are four types of DCs: display, printer, memory (or compatible), and information. Each type serves a specific purpose, as described in the following table.

Device context | Description
Display | Supports drawing operations on a video display.
Printer | Supports drawing operations on a printer or plotter.
Memory | Supports drawing operations on a bitmap.
Information | Supports the retrieval of device data.


Display Device Contexts

An application obtains a display DC by calling the BeginPaint, GetDC, or GetDCEx function and identifying the window in which the corresponding output will appear. Typically, an application obtains a display DC only when it must draw in the client area. When the application is finished drawing, it must release the DC by calling the EndPaint or ReleaseDC function.

There are three types of DCs for video displays:

  • Class
  • Common
  • Private

Class Device Contexts

Class device contexts are supported strictly for compatibility with 16-bit versions of Windows. When writing a Win32-based application, avoid using the class device context; use a private device context instead.

Common Device Contexts

Common device contexts are display DCs maintained in a special cache by the system. Common device contexts are used in applications that perform infrequent drawing operations. Before the system returns the DC handle, it initializes the common device context with default objects, attributes, and modes. Any drawing operations performed by the application use these defaults unless one of the GDI functions is called to select a new object, change the attributes of an existing object, or select a new mode.

Because only a limited number of common device contexts exist, an application should release them after it has finished drawing. When the application releases a common device context, any changes to the default data are lost.

Private Device Contexts

Private device contexts are display DCs that, unlike common device contexts, retain any changes to the default data—even after an application releases them. Private device contexts are used in applications that perform numerous drawing operations such as computer-aided design (CAD) applications, desktop-publishing applications, drawing and painting applications, and so on. Private device contexts are not part of the system cache and therefore need not be released after use. The system automatically removes a private device context after the last window of that class has been destroyed.

An application creates a private device context by first specifying the CS_OWNDC window-class style when it initializes the style member of the WNDCLASS structure and calls the RegisterClass function. (For more information about window classes, see Window Classes.)

After creating a window with the CS_OWNDC style, an application can call the GetDC, GetDCEx, or BeginPaint function once to obtain a handle identifying a private device context. The application can continue using this handle (and the associated DC) until it deletes the window created with this class. Any changes to graphic objects and their attributes, or graphic modes are retained by the system until the window is deleted.


Printer Device Contexts

The printer DC can be used when printing on a dot-matrix printer, ink-jet printer, laser printer, or plotter. An application creates a printer DC by calling the CreateDC function and supplying the appropriate arguments (the name of the printer driver, the name of the printer, the file or device name for the physical output medium, and other initialization data). When an application has finished printing, it deletes the printer DC by calling the DeleteDC function. An application must delete (rather than release) a printer DC; the ReleaseDC function fails when an application attempts to use it to release a printer DC.

For more information, see Printer Output.


Memory Device Contexts

To enable applications to place output in memory rather than sending it to an actual device, use a special device context for bitmap operations called a memory device context. A memory DC enables the system to treat a portion of memory as a virtual device. It is an array of bits in memory that an application can use temporarily to store the color data for bitmaps created on a normal drawing surface. Because the bitmap is compatible with the device, a memory DC is also sometimes referred to as a compatible device context.

The memory DC stores bitmap images for a particular device. An application can create a memory DC by calling the CreateCompatibleDC function.

The original bitmap in a memory DC is simply a placeholder. Its dimensions are one pixel by one pixel. Before an application can begin drawing, it must select a bitmap with the appropriate width and height into the DC by calling the SelectObject function. To create a bitmap of the appropriate dimensions, use the CreateBitmap, CreateBitmapIndirect, or CreateCompatibleBitmap function. After the bitmap is selected into the memory DC, the system replaces the single-bit array with an array large enough to store color information for the specified rectangle of pixels.

When an application passes the handle returned by CreateCompatibleDC to one of the drawing functions, the requested output does not appear on a device's drawing surface. Instead, the system stores the color information for the resultant line, curve, text, or region in the array of bits. The application can copy the image stored in memory back onto a drawing surface by calling the BitBlt function, identifying the memory DC as the source device context and a window or screen DC as the target device context.

When displaying a DIB or a DDB created from a DIB on a palette device, you can improve the speed at which the image is drawn by arranging the logical palette to match the layout of the system palette. To do this, call GetDeviceCaps with the NUMRESERVED value to get the number of reserved colors in the system. Then call GetSystemPaletteEntries and fill in the first and last NUMRESERVED/2 entries of the logical palette with the corresponding system colors. For example, if NUMRESERVED is 20, you would fill in the first and last 10 entries of the logical palette with the system colors. Then fill in the remaining 256-NUMRESERVED colors of the logical palette (in our example, the remaining 236 colors) with colors from the DIB and set the PC_NOCOLLAPSE flag on each of these colors.

For more information about color and palettes, see Colors. For more information about bitmaps and bitmap operations, see Bitmaps.


Information Device Contexts

The information DC is used to retrieve default device data. For example, an application can call the CreateIC function to create an information DC for a particular model of printer and then call the GetCurrentObject and GetObject functions to retrieve the default pen or brush attributes. Because the system can retrieve device information without creating the structures normally associated with the other types of device contexts, an information DC involves far less overhead and is created significantly faster than any of the other types. After an application finishes retrieving data by using an information DC, it must call the DeleteDC function.


Device Context Operations

An application can perform the following operations on a device context:

  • Enumerate existing graphic objects.
  • Select new graphic objects.
  • Delete existing graphic objects.
  • Save the current graphic objects, their attributes, and the graphic modes.
  • Restore previously saved graphic objects, their attributes, and the graphic modes.

In addition, an application can use a device context to:

  • Determine how graphics output is translated.
  • Cancel lengthy drawing operations (begun by a thread in a multithreaded application).
  • Reset a printer to a particular state.


Operations on Graphic Objects

After an application creates a display or printer DC, it can begin drawing on the associated device or, in the case of the memory DC, it can begin drawing on the bitmap stored in memory. However, before drawing begins—and sometimes while drawing is in progress—it is often necessary to replace the default objects with new objects.

An application can examine a default object's attributes by calling the GetCurrentObject and GetObject functions. The GetCurrentObject function returns a handle identifying the current pen, brush, palette, bitmap, or font, and the GetObject function initializes a structure containing that object's attributes.

Some printers provide resident pens, brushes, and fonts that can be used to improve drawing speed in an application. Two functions can be used to enumerate these objects: EnumObjects and EnumFontFamilies. If the application must enumerate resident pens or brushes, it can call the EnumObjects function to examine the corresponding attributes. If the application must enumerate resident fonts, it can call the EnumFontFamilies function (which can also enumerate GDI fonts).

Once an application determines that a default object needs replacing, it creates a new object by calling one of the following creation functions.

Graphic object | Function
Bitmap | CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDiscardableBitmap, CreateDIBitmap
Brush | CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush
Color Palette | CreatePalette
Font | CreateFont, CreateFontIndirect
Pen | CreatePen, CreatePenIndirect, ExtCreatePen
Region | CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn

Each of these functions returns a handle identifying a new object. After an application retrieves a handle, it must call the SelectObject function to replace the default object. However, the application should save the handle identifying the default object and use this handle to replace the new object when it is no longer needed. When the application finishes drawing with the new object, it must restore the default object by calling the SelectObject function and then delete the new object by calling the DeleteObject function. Failing to delete objects causes serious performance problems.


Cancellation of Drawing Operations

When complex drawing applications perform lengthy graphics operations, they consume valuable system resources. By taking advantage of the system's multitasking features, an application can use threads and the CancelDC function to manage these operations. For example, if the graphics operation performed by thread A is consuming needed resources, thread B can call the CancelDC function to halt that operation.


Retrieving Device Data

The Win32 API provides two functions that applications can use to retrieve device data using a device context: GetDeviceCaps and DeviceCapabilities.

GetDeviceCaps retrieves general device data for the following devices:

  • Raster displays
  • Dot-matrix printers
  • Ink-jet printers
  • Laser printers
  • Vector plotters
  • Raster cameras

The data includes the supported capabilities of the device, including device resolution (for video displays), color format (for video displays and color printers), number of graphic objects, raster capabilities, curve drawing, line drawing, polygon drawing, and text drawing. An application retrieves this data by supplying a handle identifying the appropriate device context, as well as an index specifying the type of data the function is to retrieve.

The DeviceCapabilities function retrieves data specific to printers, including the number of available paper bins, the duplex capabilities of the printer, the resolutions supported by the printer, the maximum and minimum supported paper size, and so on. An application retrieves this data by supplying strings specifying a printer device and port, as well as an index specifying the type of data that the function is to retrieve.


Saving, Restoring, and Resetting a Device Context

The Win32 API provides three functions that an application can use to save, restore, and reset a device context: SaveDC, RestoreDC, and ResetDC. The SaveDC function records on a special GDI stack the current DC's graphic objects and their attributes, and graphic modes. A drawing application can call this function before a user begins drawing and save the application's original state—providing a clean slate for the user. To return to this original state, the application calls the RestoreDC function.

ResetDC is provided to reset printer DC data. An application calls this function to reset the paper orientation, paper size, output scaling factor, number of copies to be printed, paper source (or bin), duplex mode, and so on. Typically, an application calls this function after a user has changed one of the printer options and the system has issued a WM_DEVMODECHANGE message.


ICM-Enabled Device Context Functions

Microsoft® Windows® 98 and Windows 2000 work with Microsoft Image Color Management (ICM). ICM technology ensures that a color image, graphic, or text object is rendered as closely as possible to its original intent on any device, despite differences in imaging technologies and color capabilities between devices. (For more information, see About Image Color Management Version 2.0.)

There are various functions in the graphics device interface (GDI) that use or operate on color data. The following device context functions are enabled for use with ICM:

  • CreateCompatibleDC
  • CreateDC
  • GetDCBrushColor
  • GetDCPenColor
  • ResetDC
  • SelectObject
  • SetDCBrushColor
  • SetDCPenColor


Using the Device Context Functions

  • Obtaining a Private Display Device Context
  • Creating a Printer Device Context
  • Retrieving the Capabilities of a Printer
  • Retrieving Graphic-Object Attributes and Selecting New Graphic Objects
  • Setting and Retrieving the Device Context Brush Color Value
  • Setting the Pen or Brush Color
  • Getting Information on a Display Monitor


Obtaining a Private Display Device Context

An application performing numerous drawing operations in the client area of its window must use a private display DC. To create this type of DC, the application must specify the CS_OWNDC constant for the style member of the WNDCLASS structure when registering the window class. After registering the window class, the application obtains a handle identifying a private display DC by calling the GetDC function.

The following example shows how to create a private display DC.

#include <windows.h>    // required for all Win32-based applications
#include <stdio.h>      // C run-time header for i/o
#include <string.h>     // C run-time header for strtok
#include "dc.h"         // specific to this program

// Function prototypes.

BOOL InitApplication(HINSTANCE);
long FAR PASCAL MainWndProc(HWND, UINT, UINT, LONG);

// Global variables

HINSTANCE hinst;       // handle to current instance
HDC hdc;               // display device context handle

BOOL InitApplication(HINSTANCE hinstance)
{
    WNDCLASS  wc;

    // Fill in the window class structure with parameters
    // describing the main window.

    wc.style = CS_OWNDC;         // Private-DC constant
    wc.lpfnWndProc = (WNDPROC) MainWndProc;

    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hinstance;

    wc.hIcon = LoadIcon((HINSTANCE) NULL,
        MAKEINTRESOURCE(IDI_APPLICATION));

    wc.hCursor = LoadCursor((HINSTANCE) NULL,
        MAKEINTRESOURCE(IDC_ARROW));

    wc.hbrBackground = GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName =  "GenericMenu";
    wc.lpszClassName = "GenericWClass";

    // Register the window class and return the resulting code.

    return RegisterClass(&wc);
}

LRESULT APIENTRY MainWndProc(
        HWND hwnd,           // window handle
        UINT message,        // type of message
        WPARAM wParam,       // additional information
        LPARAM lParam)       // additional information
{

    PAINTSTRUCT ps;              // paint structure

    // Retrieve a handle identifying the private DC.

    hdc = GetDC(hwnd);

    switch (message)
    {
        case WM_PAINT:
              BeginPaint(hwnd, &ps);

        // Draw and paint using private DC.


Creating a Printer Device Context

An application can create a printer DC in one of two ways:

  • By calling the PrintDlg function to display a common dialog box that allows the user to specify printer options, then creating a printer DC by using those options.
  • By creating a printer DC by using the default printer data from the Win.ini file.

This section contains code demonstrating the latter method.

To use the default printer, retrieve and parse the appropriate string from the Win.ini file. This string is retrieved by calling the GetProfileString function and specifying the appropriate section and entry names. In the case of the default printer, this data is stored in the [windows] section and identified by the entry named device. The seventh line in the following excerpt from a Win.ini file shows an entry for a Kodak Diconix printer.

[windows]
    load=
    run=
    Beep=yes
    Spooler=yes
    NullPort=None
    device=Diconix,winspool,LPT1:
    CoolSwitch=1
    BorderWidth=3
    KeyboardSpeed=31
    InitialKeyboardIndicators=2
    CursorBlinkRate=530
    DoubleClickSpeed=686
    Programs=com exe bat pif cmd
    Documents=
    DeviceNotSelectedTimeout=15
    TransmissionRetryTimeout=45
    swapdisk=
    NetWarn=1
    fPromptOnVerbose=FALSE
    fPromptOnWarning=FALSE
    fPromptOnError=TRUE
    fPrintVerbose=FALSE
    fPrintFileLine=FALSE
    shell=
    ScreenSaveTimeOut=300
    ScreenSaveActive=0
    DebugOptions=2048

The following example shows how a printer DC was created by using the data from Win.ini.

    HDC hdcPrint;               // printer DC handle
    char szDevString[120];      // array for WIN.INI data
    char *szPrinter, *szDriver; // printer and driver names
    char *szPort;               // port name

    // Retrieve the printer, printer driver, and
    // output-port names from WIN.INI.

    GetProfileString("windows", "device", ",,,",
        szDevString, 120);

    // Parse the string of names, setting ptrs as required
    // If the string contains the required names, use them to
    // create a device context.

    if ((szPrinter = strtok(szDevString,
               (const char *) ","))
            && (szDriver = strtok ((char *) NULL,
               (const char *) ", "))
            && (szPort = strtok ((char *) NULL,
               (const char *) ", ")))
    {
        hdcPrint = CreateDC(szDriver, szPrinter,
            szPort, NULL);
    }

    // Print a test page that contains the string
    // "PRINTER TEST" in the upper left corner.

    Escape(hdcPrint, STARTDOC, 8, "Test-Doc", NULL);
    TextOut(hdcPrint, 50, 50, "PRINTER TEST", 12);
    Escape(hdcPrint, NEWFRAME, 0, NULL, NULL);
    Escape(hdcPrint, ENDDOC, 0, NULL, NULL);

    // Delete the printer DC.

    DeleteDC(hdcPrint);


Retrieving the Capabilities of a Printer

Not every output device supports the entire set of Microsoft® Win32® graphics functions. For example, because of hardware limitations, most vector plotters do not support bit-block transfers. An application can determine whether a device supports a particular graphics function by calling the GetDeviceCaps function, specifying the appropriate index, and examining the return value.

The following example shows how an application tests a printer to determine whether it supports bit-block transfers.

// Examine the raster capabilities of the device
// identified by hdcPrint to verify that it supports
// the BitBlt function.

if ((GetDeviceCaps(hdcPrint, RASTERCAPS)
       & RC_BITBLT) == 0)
{
   DeleteDC(hdcPrint);
   break;
}

else
{
    // Print the bitmap using the printer DC.
}


Retrieving Graphic-Object Attributes and Selecting New Graphic Objects

An application can retrieve the attributes for a pen, brush, palette, font, or bitmap by calling the GetCurrentObject and GetObject functions. The GetCurrentObject function returns a handle identifying the object currently selected into the DC; the GetObject function returns a structure that describes the attributes of the object.

The following example shows how an application can retrieve the current brush attributes and use the retrieved data to determine whether it is necessary to select a new brush.

    HDC hdc;                     // display DC handle
    HBRUSH hbrushNew, hbrushOld; // brush handles
    HBRUSH hbrush;               // brush handle
    LOGBRUSH lb;                 // logical-brush structure

    // Retrieve a handle identifying the current brush.

    hbrush = GetCurrentObject(hdc, OBJ_BRUSH);

    // Retrieve a LOGBRUSH structure that contains the
    // current brush attributes.

    GetObject(hbrush, sizeof(LOGBRUSH), &lb);

    // If the current brush is not a solid-black brush,
    // replace it with the solid-black stock brush.

    if ((lb.lbStyle != BS_SOLID)
           || (lb.lbColor != 0x000000))
    {
        hbrushNew = GetStockObject(BLACK_BRUSH);
        hbrushOld = SelectObject(hdc, hbrushNew);
    }

    // Perform painting operations with the white brush.

    // After completing the last painting operation with the new
    // brush, the application should select the original brush back
    // into the device context and delete the new brush.
    // In this example, hbrushNew contains a handle to a stock object.
    // It is not necessary (but it is not harmful) to call
    // DeleteObject on a stock object. If hbrushNew contained a handle
    // to a brush created by a function such as CreateBrushIndirect,
    // it would be necessary to call DeleteObject.

    SelectObject(hdc, hbrushOld);
    DeleteObject(hbrushNew);

Note The application saved the original brush handle when calling the SelectObject function the first time. This handle is saved so that the original brush can be selected back into the DC after the last painting operation has been completed with the new brush. After the original brush is selected back into the DC, the new brush is deleted, freeing memory in the GDI heap.


Setting and Retrieving the Device Context Brush Color Value

The following example shows how an application can retrieve the current DC brush color by using the SetDCBrushColor and the GetDCBrushColor functions.

SelectObject(hdc,GetStockObject(DC_BRUSH);
SetDCBrushColor(hdc, RGB(00,0xff;00);
PatBlt(0,0,200,200,PATCOPY)
SetDCBrushColor(hdc,RGB(00,00,0xff);
PatBlt(0,0,200,200,PATCOPY);


Setting the Pen or Brush Color

The following example shows how an application can change the DC pen color by using the GetStockObject function or SetDCPenColor and the SetDCBrushColor functions.

SelectObject(hdc,GetStockObject(DC_PEN));
SetDCPenColor(hdc,RGB(00,0xff,00);
Rectangle(0,0,20,20);
SetDCPenColor(hdc,RGB(00,00,0xff));
Rectangle(0,0,20,20)

// The brush color can be changed in a similar manner. SetDCPenColor
// and SetDCBrushColor can be used interchangeably with GetStockObject
// to change the current color.

SelectObject(hDC,GetStockObject(DC_BRUSH));
SetDCBrushColor(hDC,0x0)

// Provides the same flexibility as:

SelectObject(hDC,GetStockOBject(BLACK_BRUSH));

// It is not necessary to call DeleteObject to delete stock objects.


Getting Information on a Display Monitor

The following code sample shows how to use EnumDisplayDevices to get information on a display monitor.

BOOL GetDisplayMonitorInfo(int nDeviceIndex, LPSTR lpszMonitorInfo)
{
    FARPROC EnumDisplayDevices;
    HINSTANCE  hInstUser32;
    DISPLAY_DEVICE DispDev;
    char szSaveDeviceName[32];
    BOOL bRet = TRUE;

    hInstUser32 = LoadLibrary("User32.DLL");
    if (!hInstUser32) return FALSE;

    // Get the address of the EnumDisplayDevices function
    EnumDisplayDevices = (FARPROC)GetProcAddress(hInstUser32,"EnumDisplayDevicesA");
    if (!EnumDisplayDevices) {
        FreeLibrary(hInstUser32);
        return FALSE;
    }

    ZeroMemory(&DispDev, sizeof(DISPLAY_DEVICE));
    DispDev.cb = sizeof(DISPLAY_DEVICE);

    // After the first call to EnumDisplayDevices,
    // DispDev.DeviceString is the adapter name
    if (EnumDisplayDevices(NULL, nDeviceIndex, &DispDev, 0)) {
        lstrcpy(szSaveDeviceName, DispDev.DeviceName);

        // After second call, DispDev.DeviceString is the
        // monitor name for that device
        EnumDisplayDevices(szSaveDeviceName, 0, &DispDev, 0);

        lstrcpy(lpszMonitorInfo, DispDev.DeviceString);
    } else    {
        bRet = FALSE;
    }

    FreeLibrary(hInstUser32);

    return bRet;
}


Device Context Reference

The following elements are associated with device contexts:

  • Device Context Functions
  • Device Context Structures
  • Device Context Messages


Device Context Functions

The following functions are used with device contexts.

Function | Description
CancelDC | Cancels any pending operation on the specified device context.
ChangeDisplaySettings | Changes the settings of the default display device to the specified graphics mode.
ChangeDisplaySettingsEx | Changes the settings of the specified display device to the specified graphics mode.
CreateCompatibleDC | Creates a memory device context compatible with the specified device.
CreateDC | Creates a device context for a device using the specified name.
CreateIC | Creates an information context for the specified device.
DeleteDC | Deletes the specified device context.
DeleteObject | Deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object.
DeviceCapabilities | Retrieves the capabilities of a printer device driver.
DrawEscape | Provides drawing capabilities of the specified video display that are not directly available through the graphics device interface.
EnumDisplayDevices | Retrieves information about the display devices in a system.
EnumDisplaySettings | Retrieves information about one of the graphics modes for a display device.
EnumDisplaySettingsEx | Retrieves information about one of the graphics modes for a display device.
EnumObjects | Enumerates the pens or brushes available for the specified device context.
EnumObjectsProc | An application-defined callback function used with the EnumObjects function.
GetCurrentObject | Retrieves a handle to an object of the specified type that has been selected into the specified device context.
GetDC | Retrieves a handle to a display device context for the client area of a specified window or for the entire screen.
GetDCBrushColor | Retrieves the current brush color for the specified device context.
GetDCEx | Retrieves a handle to a display device context for the client area of a specified window or for the entire screen.
GetDCOrgEx | Retrieves the final translation origin for a specified device context.
GetDCPenColor | Retrieves the current pen color for the specified device context.
GetDeviceCaps | Retrieves device-specific information for the specified device.
GetObject | Retrieves information for the specified graphics object.
GetObjectType | Retrieves the type of the specified object.
GetStockObject | Retrieves a handle to one of the stock pens, brushes, fonts, or palettes.
ReleaseDC | Releases a device context, freeing it for use by other applications.
ResetDC | Updates the specified printer or plotter device context using the specified information.
RestoreDC | Restores a device context to the specified state.
SaveDC | Saves the current state of the specified device context by copying data describing selected objects and graphic modes to a context stack.
SelectObject | Selects an object into the specified device context.
SetDCBrushColor | Sets the current device context brush color to the specified color value.
SetDCPenColor | Sets the current device context pen color to the specified color value.


CancelDC

The CancelDC function cancels any pending operation on the specified device context (DC).

BOOL CancelDC(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the DC.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The CancelDC function is used by multithreaded applications to cancel lengthy drawing operations. If thread A initiates a lengthy drawing operation, thread B may cancel that operation by calling this function.

If an operation is canceled, the affected thread returns an error and the result of its drawing operation is undefined. The results are also undefined if no drawing operation was in progress when the function was called.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateThread, GetCurrentThread


ChangeDisplaySettings

The ChangeDisplaySettings function changes the settings of the default display device to the specified graphics mode.

To change the settings of a specified display device, use the ChangeDisplaySettingsEx function.

LONG ChangeDisplaySettings(
  LPDEVMODE lpDevMode,  // graphics mode
  DWORD dwflags         // graphics mode options
);

Parameters

lpDevMode
[in] Pointer to a DEVMODE structure that describes the new graphics mode. If lpDevMode is NULL, all the values currently in the registry will be used for the display setting. Passing NULL for the lpDevMode parameter and 0 for the dwFlags parameter is the easiest way to return to the default mode after a dynamic mode change.

The dmSize member of DEVMODE must be initialized to the size, in bytes, of the DEVMODE structure. The dmDriverExtra member of DEVMODE must be initialized to indicate the number of bytes of private driver data following the DEVMODE structure. In addition, you can use any or all of the following members of the DEVMODE structure.
Member | Meaning
dmBitsPerPel | Bits per pixel
dmPelsWidth | Pixel width
dmPelsHeight | Pixel height
dmDisplayFlags | Mode flags
dmDisplayFrequency | Mode frequency
dmPosition | Windows 98/Me, Windows 2000 or later: Position of the device in a multimonitor configuration

In addition to using one or more of the preceding DEVMODE members, you must also set one or more of the following values in the dmFields member to change the display setting.
Value | Meaning
DM_BITSPERPEL | Use the dmBitsPerPel value.
DM_PELSWIDTH | Use the dmPelsWidth value.
DM_PELSHEIGHT | Use the dmPelsHeight value.
DM_DISPLAYFLAGS | Use the dmDisplayFlags value.
DM_DISPLAYFREQUENCY | Use the dmDisplayFrequency value.
DM_POSITION | Windows 98/Me, Windows 2000 or later: Use the dmPosition value.

dwflags
[in] Indicates how the graphics mode should be changed. This parameter can be one of the following values.
Value | Meaning
0 | The graphics mode for the current screen will be changed dynamically.
CDS_UPDATEREGISTRY | The graphics mode for the current screen will be changed dynamically and the graphics mode will be updated in the registry. The mode information is stored in the USER profile.
CDS_TEST | The system tests if the requested graphics mode could be set.
CDS_FULLSCREEN The mode is temporary in nature.

Windows NT/2000 or later: If you change to and from another desktop, this mode will not be reset.

CDS_GLOBAL | The settings will be saved in the global settings area so that they will affect all users on the machine. Otherwise, only the settings for the user are modified. This flag is only valid when specified with the CDS_UPDATEREGISTRY flag.
CDS_SET_PRIMARY | This device will become the primary device.
CDS_RESET | The settings should be changed, even if the requested settings are the same as the current settings.
CDS_NORESET | The settings will be saved in the registry, but will not take affect. This flag is only valid when specified with the CDS_UPDATEREGISTRY flag.

Specifying CDS_TEST allows an application to determine which graphics modes are actually valid, without causing the system to change to that graphics mode.

If CDS_UPDATEREGISTRY is specified and it is possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_SUCCESSFUL is returned. If it is not possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_RESTART is returned.

Windows NT/2000 or later: If CDS_UPDATEREGISTRY is specified and the information could not be stored in the registry, the graphics mode is not changed and DISP_CHANGE_NOTUPDATED is returned.

Return Values

The ChangeDisplaySettings function returns one of the following values.

Value | Meaning
DISP_CHANGE_SUCCESSFUL | The settings change was successful.
DISP_CHANGE_BADDUALVIEW | Whistler: The settings change was unsuccessful because system is DualView capable.
DISP_CHANGE_BADFLAGS | An invalid set of flags was passed in.
DISP_CHANGE_BADMODE | The graphics mode is not supported.
DISP_CHANGE_BADPARAM | An invalid parameter was passed in. This can include an invalid flag or combination of flags.
DISP_CHANGE_FAILED | The display driver failed the specified graphics mode.
DISP_CHANGE_NOTUPDATED | Windows NT/2000 or later: Unable to write settings to the registry.
DISP_CHANGE_RESTART | The computer must be restarted in order for the graphics mode to work.

Remarks

To ensure that the DEVMODE structure passed to ChangeDisplaySettings is valid and contains only values supported by the display driver, use the DEVMODE returned by the EnumDisplaySettings function.

When the display mode is changed dynamically, the WM_DISPLAYCHANGE message is sent to all running applications with the following message parameters.

Parameters | Meaning
wParam | New bits per pixel
LOWORD(lParam) | New pixel width
HIWORD(lParam) | New pixel height

Windows 95: If the calling thread has any top-level windows, ChangeDisplaySettings sends these windows the WM_DISPLAYCHANGE message right away (for all other windows the message is posted). This may cause the shell to get its message too soon and could squash icons. To avoid this problem, have ChangeDisplaySettings do resolution switching by calling on a thread with no windows, for example, a new thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, ChangeDisplaySettingsEx, CreateDC, DEVMODE, EnumDisplayDevices, EnumDisplaySettings, WM_DISPLAYCHANGE


ChangeDisplaySettingsEx

The ChangeDisplaySettingsEx function changes the settings of the specified display device to the specified graphics mode.

LONG ChangeDisplaySettingsEx(
  LPCTSTR lpszDeviceName,  // name of display device
  LPDEVMODE lpDevMode,     // graphics mode
  HWND hwnd,               // not used; must be NULL
  DWORD dwflags,            // graphics mode options
  LPVOID lParam            // video parameters (or NULL)
);

Parameters

lpszDeviceName
[in] Pointer to a null-terminated string that specifies the display device whose graphics mode the function will obtain information about. Only display device names as returned by EnumDisplayDevices are valid. See EnumDisplayDevices for further information on the names associated with these display devices.

The lpszDeviceName parameter can be NULL. A NULL value specifies the default display device. The default device can be determined by calling EnumDisplayDevices and checking for the DISPLAY_DEVICE_PRIMARY_DEVICE flag.

lpDevMode
[in] Pointer to a DEVMODE structure that describes the new graphics mode. If lpDevMode is NULL, all the values currently in the registry will be used for the display setting. Passing NULL for the lpDevMode parameter and 0 for the dwFlags parameter is the easiest way to return to the default mode after a dynamic mode change.

The dmSize member must be initialized to the size, in bytes, of the DEVMODE structure. The dmDriverExtra member must be initialized to indicate the number of bytes of private driver data following the DEVMODE structure. In addition, you can use any of the following members of the DEVMODE structure.
Member | Meaning
dmBitsPerPel | Bits per pixel
dmPelsWidth | Pixel width
dmPelsHeight | Pixel height
dmDisplayFlags | Mode flags
dmDisplayFrequency | Mode frequency
dmPosition | Position of the device in a multi-monitor configuration.

In addition to using one or more of the preceding DEVMODE members, you must also set one or more of the following values in the dmFields member to change the display settings.
Value | Meaning
DM_BITSPERPEL | Use the dmBitsPerPel value.
DM_PELSWIDTH | Use the dmPelsWidth value.
DM_PELSHEIGHT | Use the dmPelsHeight value.
DM_DISPLAYFLAGS | Use the dmDisplayFlags value.
DM_DISPLAYFREQUENCY | Use the dmDisplayFrequency value.
DM_POSITION | Use the dmPosition value.

hwnd
Reserved; must be NULL.
dwflags
[in] Indicates how the graphics mode should be changed. This parameter can be one of the following values.
Value | Meaning
0 | The graphics mode for the current screen will be changed dynamically.
CDS_FULLSCREEN The mode is temporary in nature.

Windows NT/2000 or later: If you change to and from another desktop, this mode will not be reset.

CDS_GLOBAL | The settings will be saved in the global settings area so that they will affect all users on the machine. Otherwise, only the settings for the user are modified. This flag is only valid when specified with the CDS_UPDATEREGISTRY flag.
CDS_NORESET | The settings will be saved in the registry, but will not take effect. This flag is only valid when specified with the CDS_UPDATEREGISTRY flag.
CDS_RESET | The settings should be changed, even if the requested settings are the same as the current settings.
CDS_SET_PRIMARY | This device will become the primary device.
CDS_TEST | The system tests if the requested graphics mode could be set.
CDS_UPDATEREGISTRY | The graphics mode for the current screen will be changed dynamically and the graphics mode will be updated in the registry. The mode information is stored in the USER profile.
CDS_VIDEOPARAMETERS | When set, the lParam parameter is a pointer to a VIDEOPARAMETERS structure.

Specifying CDS_TEST allows an application to determine which graphics modes are actually valid, without causing the system to change to them.

If CDS_UPDATEREGISTRY is specified and it is possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_SUCCESSFUL is returned. If it is not possible to change the graphics mode dynamically, the information is stored in the registry and DISP_CHANGE_RESTART is returned.

Windows NT/2000 or later: If CDS_UPDATEREGISTRY is specified and the information could not be stored in the registry, the graphics mode is not changed and DISP_CHANGE_NOTUPDATED is returned.

lParam
[in] If dwFlags is CDS_VIDEOPARAMETERS, lParam is a pointer to a VIDEOPARAMETERS structure. Otherwise lParam must be NULL.

Return Values

The ChangeDisplaySettingsEx function returns one of the following values.

Value | Meaning
DISP_CHANGE_SUCCESSFUL | The settings change was successful.
DISP_CHANGE_BADDUALVIEW | Whistler: The settings change was unsuccessful because the system is DualView capable.
DISP_CHANGE_BADFLAGS | An invalid set of flags was passed in.
DISP_CHANGE_BADMODE | The graphics mode is not supported.
DISP_CHANGE_BADPARAM | An invalid parameter was passed in. This can include an invalid flag or combination of flags.
DISP_CHANGE_FAILED | The display driver failed the specified graphics mode.
DISP_CHANGE_NOTUPDATED | Windows NT/2000 or later: Unable to write settings to the registry.
DISP_CHANGE_RESTART | The computer must be restarted for the graphics mode to work.

Remarks

To ensure that the DEVMODE structure passed to ChangeDisplaySettingsEx is valid and contains only values supported by the display driver, use the DEVMODE returned by the EnumDisplaySettings function.

When adding a display monitor to a multiple-monitor system programmatically, set DEVMODE.dmFields to DM_POSITION and specify a position (in DEVMODE.dmPosition) for the monitor you are adding that is adjacent to at least one pixel of the display area of an existing monitor. To detach the monitor, set DEVMODE.dmFields to DM_POSITION but set DEVMODE.dmPelsWidth and DEVMODE.dmPelsHeight to zero. For more information, see Multiple Display Monitors.

When the display mode is changed dynamically, the WM_DISPLAYCHANGE message is sent to all running applications with the following message parameters.

Parameters | Meaning
wParam | New bits per pixel
LOWORD(lParam) | New pixel width
HIWORD(lParam) | New pixel height

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Device Contexts Overview, Device Context Functions, CreateDC, DEVMODE, EnumDisplayDevices, EnumDisplaySettings, VIDEOPARAMETERS, WM_DISPLAYCHANGE


CreateCompatibleDC

The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device.

HDC CreateCompatibleDC(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to an existing DC. If this handle is NULL, the function creates a memory DC compatible with the application's current screen.

Return Values

If the function succeeds, the return value is the handle to a memory DC.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A memory DC exists only in memory. When the memory DC is created, its display surface is exactly one monochrome pixel wide and one monochrome pixel high. Before an application can use a memory DC for drawing operations, it must select a bitmap of the correct width and height into the DC. To select a bitmap into a DC, use the CreateCompatibleBitmap function, specifying the height, width, and color organization required.

When a memory DC is created, all attributes are set to normal default values. The memory DC can be used as a normal DC. You can set the attributes; obtain the current settings of its attributes; and select pens, brushes, and regions.

The CreateCompatibleDC function can only be used with devices that support raster operations. An application can determine whether a device supports these operations by calling the GetDeviceCaps function.

When you no longer need the memory DC, call the DeleteDC function.

ICM: If the DC that is passed to this function is enabled for Independent Color Management (ICM), the DC created by the function is ICM-enabled. The source and destination color spaces are specified in the DC.

For an example, see Capturing an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateCompatibleBitmap, DeleteDC, GetDeviceCaps


CreateDC

The CreateDC function creates a device context (DC) for a device using the specified name.

HDC CreateDC(
  LPCTSTR lpszDriver,        // driver name
  LPCTSTR lpszDevice,        // device name
  LPCTSTR lpszOutput,        // not used; should be NULL
  CONST DEVMODE* lpInitData  // optional printer data
);

Parameters

lpszDriver
Windows 95/98/Me: In Win32-based applications, lpszDriver can be NULL, WINSPL16 (a print provider), or (to obtain a display DC) it can be either the null-terminated string DISPLAY or the device name of a specific display device. If lpszDevice specifies a particular device, you must use NULL for lpszDriver.

Windows NT 4.0: Pointer to a null-terminated character string that specifies either DISPLAY or the name of a print provider, which is usually WINSPOOL.

Windows NT/2000 or later: Pointer to a null-terminated character string that specifies either DISPLAY or the name of a specific display device or the name of a print provider, which is usually WINSPOOL.

lpszDevice
[in] Pointer to a null-terminated character string that specifies the name of the specific output device being used, as shown by the Print Manager (for example, Epson FX-80). It is not the printer model name. The lpszDevice parameter must be used.

To obtain valid names for displays, call EnumDisplayDevices.

If lpszDriver is DISPLAY or the device name of a specific display device, then lpszDevice must be NULL or that same device name. If lpszDevice is NULL, then a DC is created for the primary display device.

Windows NT 3.51 and 4.0: There is only one (thus the primary) display device. Set lpszDevice to NULL.

lpszOutput
This parameter is ignored for Win32-based applications, and should be set to NULL. It is provided only for compatibility with 16-bit Windows. For more information, see the Remarks section.
lpInitData
[in] Pointer to a DEVMODE structure containing device-specific initialization data for the device driver. The DocumentProperties function retrieves this structure filled in for a specified device. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user.

If lpszDriver is DISPLAY, then lpInitData must be NULL. The display device's current DEVMODE is used.

Return Values

If the function succeeds, the return value is the handle to a DC for the specified device.

If the function fails, the return value is NULL. The function will return NULL for a DEVMODE structure other than the current DEVMODE.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Note that the handle to the DC can only be used by a single thread at any one time.

For parameters lpszDriver and lpszDevice, call EnumDisplayDevices to obtain valid names for displays.

Applications written for 16-bit versions of Windows used the lpszOutput parameter to specify a port name or to print to a file. Win32-based applications do not need to specify a port name. Win32-based applications can print to a file by calling the StartDoc function with a DOCINFO structure whose lpszOutput member specifies the path of the output file name.

When you no longer need the DC, call the DeleteDC function.

ICM: To enable ICM, set the dmICMMethod member of the DEVMODE structure (pointed to by the pInitData parameter) to the appropriate value.

For an example, see Capturing an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, Multiple Display Monitors, DeleteDC, DEVMODE, EnumDisplayDevices, DOCINFO, DocumentProperties, StartDoc


CreateIC

The CreateIC function creates an information context for the specified device. The information context provides a fast way to get information about the device without creating a device context (DC). However, GDI drawing functions cannot accept a handle to an information context.

HDC CreateIC(
  LPCTSTR lpszDriver,       // driver name
  LPCTSTR lpszDevice,       // device name
  LPCTSTR lpszOutput,       // port or file name
  CONST DEVMODE *lpdvmInit  // optional initialization data
);

Parameters

lpszDriver
[in] Pointer to a null-terminated character string that specifies the name of the device driver (for example, Epson).
lpszDevice
[in] Pointer to a null-terminated character string that specifies the name of the specific output device being used, as shown by the Print Manager (for example, Epson FX-80). It is not the printer model name. The lpszDevice parameter must be used.
lpszOutput
This parameter is ignored for Win32-based applications, and should be set to NULL. It is provided only for compatibility with 16-bit Windows. For more information, see the Remarks section.
lpdvmInit
[in] Pointer to a DEVMODE structure containing device-specific initialization data for the device driver. The DocumentProperties function retrieves this structure filled in for a specified device. The lpdvmInit parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user.

Return Values

If the function succeeds, the return value is the handle to an information context.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Applications written for 16-bit versions of Windows used the lpszOutput parameter to specify a port name or to print to a file. Win32-based applications do not need to specify a port name.

When you no longer need the information DC, call the DeleteDC function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, DeleteDC, DocumentProperties, DEVMODE, GetDeviceCaps


DeleteDC

The DeleteDC function deletes the specified device context (DC).

BOOL DeleteDC(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application must not delete a DC whose handle was obtained by calling the GetDC function. Instead, it must call the ReleaseDC function to free the DC.

For an example, see Retrieving the Capabilities of a Printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateDC, GetDC, ReleaseDC


DeleteObject

The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.

BOOL DeleteObject(
  HGDIOBJ hObject   // handle to graphic object
);

Parameters

hObject
[in] Handle to a logical pen, brush, font, bitmap, region, or palette.

Return Values

If the function succeeds, the return value is nonzero.

If the specified handle is not valid or is currently selected into a DC, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Do not delete a drawing object (pen or brush) while it is still selected into a DC.

When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.

For an example, see Creating Colored Pens and Brushes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, SelectObject


DrawEscape

The DrawEscape function provides drawing capabilities of the specified video display that are not directly available through the graphics device interface (GDI).

int DrawEscape(
  HDC hdc,            // handle to DC
  int nEscape,        // escape function
  int cbInput,        // size of structure for input
  LPCSTR lpszInData   // structure for input
);

Parameters

hdc
[in] Handle to the DC for the specified video display.
nEscape
[in] Specifies the escape function to be performed.
cbInput
[in] Specifies the number of bytes of data pointed to by the lpszInData parameter.
lpszInData
[in] Pointer to the input structure required for the specified escape.

Return Values

If the function is successful, the return value is greater than zero except for the QUERYESCSUPPORT draw escape, which checks for implementation only.

If the escape is not implemented, the return value is zero.

If an error occurred, the return value is less than zero .

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When an application calls the DrawEscape function, the data identified by cbInput and lpszInData is passed directly to the specified display driver.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions


EnumDisplayDevices

The EnumDisplayDevices function lets you obtain information about the display devices in a system.

BOOL EnumDisplayDevices(
  LPCTSTR lpDevice,                // device name
  DWORD iDevNum,                   // display device
  PDISPLAY_DEVICE lpDisplayDevice, // device information
  DWORD dwFlags                    // reserved
);

Parameters

lpDevice
[in] Pointer to the device name. If NULL, function returns information for the display adapter(s) on the machine, based on iDevNum. For more information, see Remarks.
iDevNum
[in] Index value that specifies the display device of interest.

The operating system identifies each display device with an index value. The index values are consecutive integers, starting at 0. If a system has three display devices, for example, they are specified by the index values 0, 1, and 2.

lpDisplayDevice
[out] Pointer to a DISPLAY_DEVICE structure that receives information about the display device specified by iDevNum.

Before calling EnumDisplayDevices, you must initialize the cb member of DISPLAY_DEVICE to the size, in bytes, of DISPLAY_DEVICE.

dwFlags
This parameter is currently not used and should be set to zero.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The function fails if iDevNum is greater than the largest device index.

Remarks

To query all display devices in the system, call this function in a loop, starting with iDevNum set to 0, and incrementing iDevNum until the function fails. To select all display devices in the desktop, use only the display devices that have the DISPLAY_DEVICE_ATTACHED_TO_DESKTOP flag in the DISPLAY_DEVICE structure.

To get information on the display adapter, call EnumDisplayDevices with lpDevice set to NULL. For example, DISPLAY_DEVICE.DeviceString contains the adapter name.

To obtain information on a display monitor, first call EnumDisplayDevices with lpDevice set to NULL. Then call EnumDisplayDevices with lpDevice set to DISPLAY_DEVICE.DeviceName from the first call to EnumDisplayDevices and with iDevNum set to zero. Then DISPLAY_DEVICE.DeviceString is the monitor name.

If an adapter has multiple monitors, to obtain information on all of them you must repeatedly call EnumDisplayDevices. Each time you call the function, set lpDevice to the adapter name and increment iDevNum. Note thatDISPLAY_DEVICE.DeviceName changes with each call for monitor information, so you must save the adapter name. The function fails when there are no more monitors for the adapter.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Device Contexts Overview, Device Context Functions, ChangeDisplaySettings, ChangeDisplaySettingsEx, CreateDC, DEVMODE, DISPLAY_DEVICE , EnumDisplaySettings


EnumDisplaySettings

The EnumDisplaySettings function retrieves information about one of the graphics modes for a display device. To retrieve information for all the graphics modes of a display device, make a series of calls to this function.

BOOL EnumDisplaySettings(
  LPCTSTR lpszDeviceName,  // display device
  DWORD iModeNum,          // graphics mode
  LPDEVMODE lpDevMode      // graphics mode settings
);

Parameters

lpszDeviceName
[in] Pointer to a null-terminated string that specifies the display device about whose graphics mode the function will obtain information.

This parameter is either NULL or a DISPLAY_DEVICE .DeviceName returned from EnumDisplayDevices. A NULL value specifies the current display device on the computer on which the calling thread is running.

Windows 95: lpszDeviceName must be NULL.

iModeNum
[in] Specifies the type of information to retrieve. This value can be a graphics mode index or one of the following values.
Value | Meaning
ENUM_CURRENT_SETTINGS | Retrieve the current settings for the display device.
ENUM_REGISTRY_SETTINGS | Retrieve the settings for the display device that are currently stored in the registry.

Graphics mode indexes start at zero. To obtain information for all of a display device's graphics modes, make a series of calls to EnumDisplaySettings, as follows: Set iModeNum to zero for the first call, and increment iModeNum by one for each subsequent call. Continue calling the function until the return value is zero.

When you call EnumDisplaySettings with iModeNum set to zero, the operating system initializes and caches information about the display device. When you call EnumDisplaySettings with iModeNum set to a non-zero value, the function returns the information that was cached the last time the function was called with iModeNum set to zero.

lpDevMode
[out] Pointer to a DEVMODE structure into which the function stores information about the specified graphics mode. Before calling EnumDisplaySettings, set the dmSize member to sizeof(DEVMODE), and set the dmDriverExtra member to indicate the size, in bytes, of the additional space available to receive private driver data.

The EnumDisplaySettings function sets values for the following five DEVMODE members:

  • dmBitsPerPel
  • dmPelsWidth
  • dmPelsHeight
  • dmDisplayFlags
  • dmDisplayFrequency

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The function fails if iModeNum is greater than the index of the display device's last graphics mode. As noted in the description of the iModeNum parameter, you can use this behavior to enumerate all of a display device's graphics modes.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, ChangeDisplaySettings, ChangeDisplaySettingsEx, CreateDC, CreateDesktop, DEVMODE, DISPLAY_DEVICE, EnumDisplayDevices


EnumDisplaySettingsEx

The EnumDisplaySettingsEx function retrieves information about one of the graphics modes for a display device. To retrieves information for all the graphics modes for a display device, make a series of calls to this function.

This function differs from EnumDisplaySettings in that there is a dwFlags parameter.

BOOL EnumDisplaySettingsEx(
  LPCTSTR lpszDeviceName,  // display device
  DWORD iModeNum,          // graphics mode
  LPDEVMODE lpDevMode,      // graphics mode settings
  DWORD dwFlags            // options
);

Parameters

lpszDeviceName
[in] Pointer to a null-terminated string that specifies the display device about which graphics mode the function will obtain information.

This parameter is either NULL or aDISPLAY_DEVICE.DeviceName returned from EnumDisplayDevices. A NULL value specifies the current display device on the computer that the calling thread is running on.

iModeNum
[in] Indicates the type of information to retrieve. This value can be a graphics mode index or one of the following values.
Value | Meaning
ENUM_CURRENT_SETTINGS | Retrieve the current settings for the display device.
ENUM_REGISTRY_SETTINGS | Retrieve the settings for the display device that are currently stored in the registry.

Graphics mode indexes start at zero. To obtain information for all of a display device's graphics modes, make a series of calls to EnumDisplaySettingsEx, as follows: Set iModeNum to zero for the first call, and increment iModeNum by one for each subsequent call. Continue calling the function until the return value is zero.

When you call EnumDisplaySettingsEx with iModeNum set to zero, the operating system initializes and caches information about the display device. When you call EnumDisplaySettingsEx with iModeNum set to a nonzero value, the function returns the information that was cached the last time the function was called with iModeNum set to zero.

lpDevMode
[out] Pointer to a DEVMODE structure into which the function stores information about the specified graphics mode. Before calling EnumDisplaySettingsEx, set the dmSize member to sizeof(DEVMODE), and set the dmDriverExtra member to indicate the size, in bytes, of the additional space available to receive private driver data.

The EnumDisplaySettingsEx function sets values for the following five DEVMODE members:

  • dmBitsPerPel
  • dmPelsWidth
  • dmPelsHeight
  • dmDisplayFlags
  • dmDisplayFrequency
dwFlags
[in] This parameter can be the following value.
Value | Meaning
EDS_RAWMODE | If set, the function will return all graphics modes reported by the adapter driver, regardless of monitor capabilities. Otherwise, it will only return modes that are compatible with current monitors.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

To get extended error information, call GetLastError.

Remarks

The function fails if iModeNum is greater than the index of the display device's last graphics mode. As noted in the description of the iModeNum parameter, you can use this behavior to enumerate all of a display device's graphics modes.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Device Contexts Overview, Device Context Functions, ChangeDisplaySettings, ChangeDisplaySettingsEx, CreateDC, CreateDesktop, DEVMODE, DISPLAY_DEVICE, EnumDisplaySettings, EnumDisplayDevices


EnumObjects

The EnumObjects function enumerates the pens or brushes available for the specified device context (DC). This function calls the application-defined callback function once for each available object, supplying data describing that object. EnumObjects continues calling the callback function until the callback function returns zero or until all of the objects have been enumerated.

int EnumObjects(
  HDC hdc,                    // handle to DC
  int nObjectType,            // object-type identifier
  GOBJENUMPROC lpObjectFunc,  // callback function
  LPARAM lParam               // application-supplied data
);

Parameters

hdc
[in] Handle to the DC.
nObjectType
[in] Specifies the object type. This parameter can be OBJ_BRUSH or OBJ_PEN.
lpObjectFunc
[in] Pointer to the application-defined callback function. For more information about the callback function, see the EnumObjectsProc function.
lParam
[in] Pointer to the application-defined data. The data is passed to the callback function along with the object information.

Return Values

If the function succeeds, the return value is the last value returned by the callback function. Its meaning is user-defined.

If there are too many objects to enumerate, the function returns –1. In this case, the callback function is not called.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, EnumObjectsProc, GetObject


EnumObjectsProc

The EnumObjectsProc function is an application-defined callback function used with the EnumObjects function. It is used to process the object data. The GOBJENUMPROC type defines a pointer to this callback function. EnumObjectsProc is a placeholder for the application-defined function name.

int CALLBACK EnumObjectsProc(
  LPVOID lpLogObject,  // object attributes
  LPARAM lpData        // application-defined data
);

Parameters

lpLogObject
[in] Pointer to a LOGPEN or LOGBRUSH structure describing the attributes of the object.
lpData
[in] Pointer to the application-defined data passed by the EnumObjects function.

Return Values

To continue enumeration, the callback function must return a nonzero value. This value is user-defined.

To stop enumeration, the callback function must return zero.

Remarks

An application must register this function by passing its address to the EnumObjects function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Device Contexts Overview, Device Context Functions, EnumObjects, GlobalAlloc, GlobalLock, LOGPEN, LOGBRUSH


GetCurrentObject

The GetCurrentObject function retrieves a handle to an object of the specified type that has been selected into the specified device context (DC).

HGDIOBJ GetCurrentObject(
  HDC hdc,           // handle to DC
  UINT uObjectType   // object type
);

Parameters

hdc
[in] Handle to the DC.
uObjectType
[in] Specifies the object type to be queried. This parameter can be one of the following values.
Value | Meaning
OBJ_BITMAP | Returns the current selected bitmap.
OBJ_BRUSH | Returns the current selected brush.
OBJ_COLORSPACE | Returns the current color space.
OBJ_FONT | Returns the current selected font.
OBJ_PAL | Returns the current selected palette.
OBJ_PEN | Returns the current selected pen.

Return Values

If the function succeeds, the return value is a handle to the specified object.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can use the GetCurrentObject and GetObject functions to retrieve descriptions of the graphic objects currently selected into the specified DC.

For an example, see Retrieving Graphic-Object Attributes and Selecting New Graphic Objects.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, DeleteObject, GetObject, SelectObject, CreateColorSpace


GetDC

The GetDC function retrieves a handle to a display device context (DC) for the client area of a specified window or for the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC.

The GetDCEx function is an extension to GetDC, which gives an application more control over how and whether clipping occurs in the client area.

HDC GetDC(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] Handle to the window whose DC is to be retrieved. If this value is NULL, GetDC retrieves the DC for the entire screen.

Windows 98/Me, Windows 2000 or later: To get the DC for a specific display monitor, use the EnumDisplayMonitors and CreateDC functions.

Return Values

If the function succeeds, the return value is a handle to the DC for the specified window's client area.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The GetDC function retrieves a common, class, or private DC depending on the class style specified for the specified window. For common DCs, GetDC assigns default attributes to the DC each time it is retrieved. For class and private DCs, GetDC leaves the previously assigned attributes unchanged.

Note that the handle to the DC can only be used by a single thread at any one time.

After painting with a common DC, the ReleaseDC function must be called to release the DC. Class and private DCs do not have to be released. ReleaseDC must be called from the same thread that called GetDC. The number of DCs is limited only by available memory.

Windows 95/98/Me: There are only 5 common DCs available per thread, thus failure to release a DC can prevent other applications from accessing one.

For an example, see Drawing with the Mouse.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Device Contexts Overview, Device Context Functions, GetDCEx, ReleaseDC, GetWindowDC


GetDCBrushColor

The GetDCBrushColor function retrieves the current brush color for the specified device context (DC).

COLORREF GetDCBrushColor(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the DC whose brush color is to be returned.

Return Values

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

If the function fails, the return value is CLR_INVALID.

Remarks

For information on setting the brush color, see SetDCBrushColor.

ICM: Color management is performed if ICM is enabled.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Included as a resource in Msimg32.dll.

See Also

Device Contexts Overview, Device Context Functions, SetDCBrushColor, COLORREF


GetDCEx

The GetDCEx function retrieves a handle to a display device context (DC) for the client area of a specified window or for the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC.

This function is an extension to the GetDC function, which gives an application more control over how and whether clipping occurs in the client area.

HDC GetDCEx(
  HWND hWnd,      // handle to window
  HRGN hrgnClip,  // handle to clipping region
  DWORD flags     // creation options
);

Parameters

hWnd
[in] Handle to the window whose DC is to be retrieved. If this value is NULL, GetDCEx retrieves the DC for the entire screen.

Windows 98/Me, Windows 2000 or later: To get the DC for a specific display monitor, use the EnumDisplayMonitors and CreateDC functions.

hrgnClip
[in] Specifies a clipping region that may be combined with the visible region of the DC. If the value of flags is DCX_INTERSECTRGN or DCX_EXCLUDERGN, then the operating system assumes ownership of the region and will automatically delete it when it is no longer needed. In this case, applications should not use the region—not even delete it—after a successful call to GetDCEx.
flags
[in] Specifies how the DC is created. This parameter can be one or more of the following values.
Value | Meaning
DCX_WINDOW | Returns a DC that corresponds to the window rectangle rather than the client rectangle.
DCX_CACHE | Returns a DC from the cache, rather than the OWNDC or CLASSDC window. Essentially overrides CS_OWNDC and CS_CLASSDC.
DCX_PARENTCLIP | Uses the visible region of the parent window. The parent's WS_CLIPCHILDREN and CS_PARENTDC style bits are ignored. The origin is set to the upper-left corner of the window identified by hWnd.
DCX_CLIPSIBLINGS | Excludes the visible regions of all sibling windows above the window identified by hWnd.
DCX_CLIPCHILDREN | Excludes the visible regions of all child windows below the window identified by hWnd.
DCX_NORESETATTRS | Does not reset the attributes of this DC to the default attributes when this DC is released.
DCX_LOCKWINDOWUPDATE | Allows drawing even if there is a LockWindowUpdate call in effect that would otherwise exclude this window. Used for drawing during tracking.
DCX_EXCLUDERGN | The clipping region identified by hrgnClip is excluded from the visible region of the returned DC.
DCX_INTERSECTRGN | The clipping region identified by hrgnClip is intersected with the visible region of the returned DC.
DCX_VALIDATE | When specified with DCX_INTERSECTUPDATE, causes the DC to be completely validated. Using this function with both DCX_INTERSECTUPDATE and DCX_VALIDATE is identical to using the BeginPaint function.

Return Values

If the function succeeds, the return value is the handle to the DC for the specified window.

If the function fails, the return value is NULL. An invalid value for the hWnd parameter will cause the function to fail.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Unless the display DC belongs to a window class, the ReleaseDC function must be called to release the DC after painting. Also, ReleaseDC must be called from the same thread that called GetDCEx. The number of DCs is limited only by available memory.

Windows 95/98: There are only five common DCs available at any time, thus failure to release a DC can prevent other applications from accessing one.

The function returns a handle to a DC that belongs to the window's class if CS_CLASSDC, CS_OWNDC or CS_PARENTDC was specified as a style in the WNDCLASS structure when the class was registered.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Device Contexts Overview, Device Context Functions, BeginPaint, GetWindowDC, ReleaseDC, WNDCLASS


GetDCOrgEx

The GetDCOrgEx function retrieves the final translation origin for a specified device context (DC). The final translation origin specifies an offset that the system uses to translate device coordinates into client coordinates (for coordinates in an application's window).

BOOL GetDCOrgEx(
  HDC hdc,          // handle to a DC
  LPPOINT lpPoint   // translation origin
);

Parameters

hdc
[in] Handle to the DC whose final translation origin is to be retrieved.
lpPoint
[out] Pointer to a POINT structure that receives the final translation origin, in device coordinates.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The final translation origin is relative to the physical origin of the screen.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateIC, POINT


GetDCPenColor

The GetDCPenColor function retrieves the current pen color for the specified device context (DC).

COLORREF GetDCPenColor(
  HDC hdc  // handle to DC
);

Parameters

hdc
[in] Handle to the DC whose brush color is to be returned.

Return Values

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

If the function fails, the return value is CLR_INVALID.

Remarks

For information on setting the pen color, see SetDCPenColor.

ICM: Color management is performed if ICM is enabled.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Included as a resource in Msimg32.dll.

See Also

Device Contexts Overview, Device Context Functions, COLORREF, SetDCPenColor


GetDeviceCaps

The GetDeviceCaps function retrieves device-specific information for the specified device.

int GetDeviceCaps(
  HDC hdc,     // handle to DC
  int nIndex   // index of capability
);

Parameters

hdc
[in] Handle to the DC.
nIndex
[in] Specifies the item to return. This parameter can be one of the following values.
Index | Meaning
DRIVERVERSION | The device driver version.
TECHNOLOGY | Device technology. It can be any one of the following values.
DT_PLOTTER | Vector plotter
DT_RASDISPLAY | Raster display
DT_RASPRINTER | Raster printer
DT_RASCAMERA | Raster camera
DT_CHARSTREAM | Character stream
DT_METAFILE | Metafile
DT_DISPFILE | Display file
If the hdc parameter is a handle to the DC of an enhanced metafile, the device technology is that of the referenced device as specified to the CreateEnhMetaFile function. To determine whether it is an enhanced metafile DC, use the GetObjectType function.
HORZSIZE | Width, in millimeters, of the physical screen.
VERTSIZE | Height, in millimeters, of the physical screen.
HORZRES | Width, in pixels, of the screen.
VERTRES | Height, in raster lines, of the screen.
LOGPIXELSX | Number of pixels per logical inch along the screen width. In a system with multiple display monitors, this value is the same for all monitors.
LOGPIXELSY | Number of pixels per logical inch along the screen height. In a system with multiple display monitors, this value is the same for all monitors.
BITSPIXEL | Number of adjacent color bits for each pixel.
PLANES | Number of color planes.
NUMBRUSHES | Number of device-specific brushes.
NUMPENS | Number of device-specific pens.
NUMFONTS | Number of device-specific fonts.
NUMCOLORS | Number of entries in the device's color table, if the device has a color depth of no more than 8 bits per pixel. For devices with greater color depths, – 1 is returned.
ASPECTX | Relative width of a device pixel used for line drawing.
ASPECTY | Relative height of a device pixel used for line drawing.
ASPECTXY | Diagonal width of the device pixel used for line drawing.
PDEVICESIZE | Reserved.
CLIPCAPS | Flag that indicates the clipping capabilities of the device. If the device can clip to a rectangle, it is 1. Otherwise, it is 0.
SIZEPALETTE | Number of entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with 16-bit Windows.
NUMRESERVED | Number of reserved entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with 16-bit Windows.
COLORRES | Actual color resolution of the device, in bits per pixel. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index and is available only if the driver is compatible with 16-bit Windows.
PHYSICALWIDTH | For printing devices: the width of the physical page, in device units. For example, a printer set to print at 600 dpi on 8.5-x11-inch paper has a physical width value of 5100 device units. Note that the physical page is almost always greater than the printable area of the page, and never smaller.
PHYSICALHEIGHT | For printing devices: the height of the physical page, in device units. For example, a printer set to print at 600 dpi on 8.5-by-11-inch paper has a physical height value of 6600 device units. Note that the physical page is almost always greater than the printable area of the page, and never smaller.
PHYSICALOFFSETX | For printing devices: the distance from the left edge of the physical page to the left edge of the printable area, in device units. For example, a printer set to print at 600 dpi on 8.5-by-11-inch paper, that cannot print on the leftmost 0.25-inch of paper, has a horizontal physical offset of 150 device units.
PHYSICALOFFSETY | For printing devices: the distance from the top edge of the physical page to the top edge of the printable area, in device units. For example, a printer set to print at 600 dpi on 8.5-by-11-inch paper, that cannot print on the topmost 0.5-inch of paper, has a vertical physical offset of 300 device units.
VREFRESH Windows NT/2000 or later: For display devices: the current vertical refresh rate of the device, in cycles per second (Hz).

A vertical refresh rate value of 0 or 1 represents the display hardware's default refresh rate. This default rate is typically set by switches on a display card or computer motherboard, or by a configuration program that does not use Win32 display functions such as ChangeDisplaySettings.

SCALINGFACTORX | Scaling factor for the x-axis of the printer.
SCALINGFACTORY | Scaling factor for the y-axis of the printer.
BLTALIGNMENT | Windows NT/2000 or later: Preferred horizontal drawing alignment, expressed as a multiple of pixels. For best drawing performance, windows should be horizontally aligned to a multiple of this value. A value of zero indicates that the device is accelerated, and any alignment may be used.
SHADEBLENDCAPS | Windows 98/Me, Windows 2000 or later: Value that indicates the shading and blending capabilities of the device.
SB_CONST_ALPHA | Handles the SourceConstantAlpha member of the BLENDFUNCTION structure, which is referenced by the blendFunction parameter of the AlphaBlend function.
SB_GRAD_RECT | Capable of doing GradientFill rectangles.
SB_GRAD_TRI | Capable of doing GradientFill triangles.
SB_NONE | Device does not support any of these capabilities.
SB_PIXEL_ALPHA | Capable of handling per-pixel alpha in AlphaBlend.
SB_PREMULT_ALPHA | Capable of handling premultiplied alpha in AlphaBlend.
RASTERCAPS | Value that indicates the raster capabilities of the device, as shown in the following table.
RC_BANDING | Requires banding support.
RC_BITBLT | Capable of transferring bitmaps.
RC_BITMAP64 | Capable of supporting bitmaps larger than 64 KB.
RC_DI_BITMAP | Capable of supporting the SetDIBits and GetDIBits functions.
RC_DIBTODEV | Capable of supporting the SetDIBitsToDevice function.
RC_FLOODFILL | Capable of performing flood fills.
RC_GDI20_OUTPUT | Capable of supporting features of 16-bit Windows 2.0.
RC_PALETTE | Specifies a palette-based device.
RC_SCALING | Capable of scaling.
RC_STRETCHBLT | Capable of performing the StretchBlt function.
RC_STRETCHDIB | Capable of performing the StretchDIBits function.
CURVECAPS | Value that indicates the curve capabilities of the device, as shown in the following table:
CC_NONE | Device does not support curves.
CC_CHORD | Device can draw chord arcs.
CC_CIRCLES | Device can draw circles.
CC_ELLIPSES | Device can draw ellipses.
CC_INTERIORS | Device can draw interiors.
CC_PIE | Device can draw pie wedges.
CC_ROUNDRECT | Device can draw rounded rectangles.
CC_STYLED | Device can draw styled borders.
CC_WIDE | Device can draw wide borders.
CC_WIDESTYLED | Device can draw borders that are wide and styled.
LINECAPS | Value that indicates the line capabilities of the device, as shown in the following table:
LC_NONE | Device does not support lines.
LC_INTERIORS | Device can draw interiors.
LC_MARKER | Device can draw a marker.
LC_POLYLINE | Device can draw a polyline.
LC_POLYMARKER | Device can draw multiple markers.
LC_STYLED | Device can draw styled lines.
LC_WIDE | Device can draw wide lines.
LC_WIDESTYLED | Device can draw lines that are wide and styled.
POLYGONALCAPS | Value that indicates the polygon capabilities of the device, as shown in the following table.
PC_NONE | Device does not support polygons.
PC_INTERIORS | Device can draw interiors.
PC_POLYGON | Device can draw alternate-fill polygons.
PC_RECTANGLE | Device can draw rectangles.
PC_SCANLINE | Device can draw a single scanline.
PC_STYLED | Device can draw styled borders.
PC_WIDE | Device can draw wide borders.
PC_WIDESTYLED | Device can draw borders that are wide and styled.
PC_WINDPOLYGON | Device can draw winding-fill polygons.
TEXTCAPS | Value that indicates the text capabilities of the device, as shown in the following table.
TC_OP_CHARACTER | Device is capable of character output precision.
TC_OP_STROKE | Device is capable of stroke output precision.
TC_CP_STROKE | Device is capable of stroke clip precision.
TC_CR_90 | Device is capable of 90-degree character rotation.
TC_CR_ANY | Device is capable of any character rotation.
TC_SF_X_YINDEP | Device can scale independently in the x- and y-directions.
TC_SA_DOUBLE | Device is capable of doubled character for scaling.
TC_SA_INTEGER | Device uses integer multiples only for character scaling.
TC_SA_CONTIN | Device uses any multiples for exact character scaling.
TC_EA_DOUBLE | Device can draw double-weight characters.
TC_IA_ABLE | Device can italicize.
TC_UA_ABLE | Device can underline.
TC_SO_ABLE | Device can draw strikeouts.
TC_RA_ABLE | Device can draw raster fonts.
TC_VA_ABLE | Device can draw vector fonts.
TC_RESERVED | Reserved; must be zero.
TC_SCROLLBLT | Device cannot scroll using a bit-block transfer. Note that this meaning may be the opposite of what you expect.
COLORMGMTCAPS | Windows 2000 or later: Value that indicates the color management capabilities of the device.
CM_CMYK_COLOR | Device can accept CMYK color space ICC color profile.
CM_DEVICE_ICM | Device can perform ICM on either the device driver or the device itself.
CM_GAMMA_RAMP | Device supports GetDeviceGammaRamp and SetDeviceGammaRamp
CM_NONE | Device does not support ICM.

Return Values

The return value specifies the value of the desired item.

When nIndex is BITSPIXEL and the device has 15bpp or 16bpp, the return value is 16.

Remarks

GetDeviceCaps provides the following six indexes in place of printer escapes.

Index | Printer escape replaced
PHYSICALWIDTH | GETPHYSPAGESIZE
PHYSICALHEIGHT | GETPHYSPAGESIZE
PHYSICALOFFSETX | GETPRINTINGOFFSET
PHYSICALOFFSETY | GETPHYSICALOFFSET
SCALINGFACTORX | GETSCALINGFACTOR
SCALINGFACTORY | GETSCALINGFACTOR

For an example, see Preparing to Print.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateEnhMetaFile, CreateIC, DeviceCapabilities, GetDIBits, GetObjectType, SetDIBits, SetDIBitsToDevice, StretchBlt, StretchDIBits


GetObject

The GetObject function retrieves information for the specified graphics object.

int GetObject(
  HGDIOBJ hgdiobj,  // handle to graphics object
  int cbBuffer,     // size of buffer for object information
  LPVOID lpvObject  // buffer for object information
);

Parameters

hgdiobj
[in] Handle to the graphics object of interest. This can be a handle to one of the following: a logical bitmap, a brush, a font, a palette, a pen, or a device independent bitmap created by calling the CreateDIBSection function.
cbBuffer
[in] Specifies the number of bytes of information to be written to the buffer.
lpvObject
[out] Pointer to a buffer that receives the information about the specified graphics object.

The following table shows the type of information the buffer receives for each type of graphics object you can specify with hgdiobj.
Object type | Data written to buffer
HBITMAP | BITMAP
HBITMAP returned from a call to CreateDIBSection | DIBSECTION, if cbBuffer is set to sizeof(DIBSECTION), or BITMAP, if cbBuffer is set to sizeof(BITMAP)
HPALETTE | A WORD count of the number of entries in the logical palette
HPEN returned from a call to ExtCreatePen | EXTLOGPEN
HPEN | LOGPEN
HBRUSH | LOGBRUSH
HFONT | LOGFONT

If the lpvObject parameter is NULL, the function return value is the number of bytes required to store the information it writes to the buffer for the specified graphics object.

Return Values

If the function succeeds, and lpvObject is a valid pointer, the return value is the number of bytes stored into the buffer.

If the function succeeds, and lpvObject is NULL, the return value is the number of bytes required to hold the information the function would store into the buffer.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The buffer pointed to by the lpvObject parameter must be sufficiently large to receive the information about the graphics object. Depending on the graphics object, the function uses a BITMAP, DIBSECTION, EXTLOGPEN, LOGBRUSH, LOGFONT, or LOGPEN structure, or a count of table entries (for a logical palette).

If hgdiobj is a handle to a bitmap created by calling CreateDIBSection, and the specified buffer is large enough, the GetObject function returns a DIBSECTION structure. In addition, the bmBits member of the BITMAP structure contained within the DIBSECTION will contain a pointer to the bitmap's bit values.

If hgdiobj is a handle to a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.

If hgdiobj is a handle to a logical palette, GetObject retrieves a 2-byte integer that specifies the number of entries in the palette. The function does not retrieve the LOGPALETTE structure defining the palette. To retrieve information about palette entries, an application can call the GetPaletteEntries function.

If hgdiobj is a handle to a font, the LOGFONT that is returned is the LOGFONT used to create the font. If Windows had to make some interpolation of the font because the precise LOGFONT could not be represented, the interpolation will not be reflected in the LOGFONT. For example, if you ask for a vertical version of a font that doesn't support vertical painting, the LOGFONT indicates the font is vertical, but Windows will paint it horizontally.

For an example, see Storing an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, CreateDIBSection, GetBitmapBits, GetDIBits, GetPaletteEntries, GetRegionData, BITMAP, DIBSECTION, EXTLOGPEN, LOGBRUSH, LOGFONT, LOGPALETTE, LOGPEN


GetObjectType

The GetObjectType retrieves the type of the specified object.

DWORD GetObjectType(
  HGDIOBJ h   // handle to graphics object
);

Parameters

h
[in] Handle to the graphics object.

Return Values

If the function succeeds, the return value identifies the object. This value can be one of the following.

Value | Meaning
OBJ_BITMAP | Bitmap
OBJ_BRUSH | Brush
OBJ_COLORSPACE | Color space
OBJ_DC | Device context
OBJ_ENHMETADC | Enhanced metafile DC
OBJ_ENHMETAFILE | Enhanced metafile
OBJ_EXTPEN | Extended pen
OBJ_FONT | Font
OBJ_MEMDC | Memory DC
OBJ_METAFILE | Metafile
OBJ_METADC | Metafile DC
OBJ_PAL | Palette
OBJ_PEN | Pen
OBJ_REGION | Region

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, GetObject, SelectObject


GetStockObject

The GetStockObject function retrieves a handle to one of the stock pens, brushes, fonts, or palettes.

HGDIOBJ GetStockObject(
  int fnObject   // stock object type
);

Parameters

fnObject
[in] Specifies the type of stock object. This parameter can be one of the following values.
Value | Meaning
BLACK_BRUSH | Black brush.
DKGRAY_BRUSH | Dark gray brush.
DC_BRUSH | Windows 2000 or later: Solid color brush. The default color is white. The color can be changed by using the SetDCBrushColor function. For more information, see the Remarks section.
GRAY_BRUSH | Gray brush.
HOLLOW_BRUSH | Hollow brush (equivalent to NULL_BRUSH).
LTGRAY_BRUSH | Light gray brush.
NULL_BRUSH | Null brush (equivalent to HOLLOW_BRUSH).
WHITE_BRUSH | White brush.
BLACK_PEN | Black pen.
DC_PEN | Windows 2000 or later: Solid pen color. The default color is white. The color can be changed by using the SetDCPenColor function. For more information, see the Remarks section.
WHITE_PEN | White pen.
ANSI_FIXED_FONT | Windows fixed-pitch (monospace) system font.
ANSI_VAR_FONT | Windows variable-pitch (proportional space) system font.
DEVICE_DEFAULT_FONT | Windows NT/2000 or later: Device-dependent font.
DEFAULT_GUI_FONT | Default font for user interface objects such as menus and dialog boxes. This is MS Sans Serif. Compare this with SYSTEM_FONT.
OEM_FIXED_FONT | Original equipment manufacturer (OEM) dependent fixed-pitch (monospace) font.
SYSTEM_FONT System font. By default, the system uses the system font to draw menus, dialog box controls, and text.

Windows 95/98 and NT: The system font is MS Sans Serif.

Windows 2000 or later: The system font is Tahoma
SYSTEM_FIXED_FONT | Fixed-pitch (monospace) system font. This stock object is provided only for compatibility with 16-bit Windows versions earlier than 3.0.
DEFAULT_PALETTE | Default palette. This palette consists of the static colors in the system palette.

Return Values

If the function succeeds, the return value is a handle to the requested logical object.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Use the DKGRAY_BRUSH, GRAY_BRUSH, and LTGRAY_BRUSH stock objects only in windows with the CS_HREDRAW and CS_VREDRAW styles. Using a gray stock brush in any other style of window can lead to misalignment of brush patterns after a window is moved or sized. The origins of stock brushes cannot be adjusted.

The HOLLOW_BRUSH and NULL_BRUSH stock objects are equivalent.

The font used by the DEFAULT_GUI_FONT stock object could change. Use this stock object when you want to use the font that menus, dialog boxes, and other user interface objects use.

It is not necessary (but it is not harmful) to delete stock objects by calling DeleteObject.

Windows 2000 or later: Both DC_BRUSH and DC_PEN can be used interchangeably with other stock objects like BLACK_BRUSH and BLACK_PEN. For information on retrieving the current pen or brush color, see GetDCBrushColor and GetDCPenColor. See Setting the Pen or Brush Color for an example of setting colors. The GetStockObject function with an argument of DC_BRUSH or DC_PEN can be used interchangeably with the SetDCPenColor and SetDCBrushColor functions.

For an example, see Setting the Pen or Brush Color.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, DeleteObject, SelectObject


ReleaseDC

The ReleaseDC function releases a device context (DC), freeing it for use by other applications. The effect of the ReleaseDC function depends on the type of DC. It frees only common and window DCs. It has no effect on class or private DCs.

int ReleaseDC(
  HWND hWnd,  // handle to window
  HDC hDC     // handle to DC
);

Parameters

hWnd
[in] Handle to the window whose DC is to be released.
hDC
[in] Handle to the DC to be released.

Return Values

The return value indicates whether the DC was released. If the DC was released, the return value is 1.

If the DC was not released, the return value is zero.

Remarks

The application must call the ReleaseDC function for each call to the GetWindowDC function and for each call to the GetDC function that retrieves a common DC.

An application cannot use the ReleaseDC function to release a DC that was created by calling the CreateDC function; instead, it must use the DeleteDC function. ReleaseDC must be called from the same thread that called GetDC.

For an example, see Scaling an Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Device Contexts Overview, Device Context Functions, CreateDC, DeleteDC, GetDC, GetWindowDC


ResetDC

The ResetDC function updates the specified printer or plotter device context (DC) using the specified information.

HDC ResetDC(
  HDC hdc,                   // handle to DC
  CONST DEVMODE *lpInitData  // DC information
);

Parameters

hdc
[in] Handle to the DC to update.
lpInitData
[in] Pointer to a DEVMODE structure containing information about the new DC.

Return Values

If the function succeeds, the return value is a handle to the original DC.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application will typically use the ResetDC function when a window receives a WM_DEVMODECHANGE message. ResetDC can also be used to change the paper orientation or paper bins while printing a document.

The ResetDC function cannot be used to change the driver name, device name, or the output port. When the user changes the port connection or device name, the application must delete the original DC and create a new DC with the new information.

An application can pass an information DC to the ResetDC function. In that situation, ResetDC will always return a printer DC.

ICM: The color profile of the DC specified by the hdc parameter will be reset based on the information contained in the lpInitData member of the DEVMODE structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Device Contexts Overview, Device Context Functions, DeviceCapabilities, DEVMODE, Escape


RestoreDC

The RestoreDC function restores a device context (DC) to the specified state. The DC is restored by popping state information off a stack created by earlier calls to the SaveDC function.

BOOL RestoreDC(
  HDC hdc,       // handle to DC
  int nSavedDC   // restore state
);

Parameters

hdc
[in] Handle to the DC.
nSavedDC
[in] Specifies the saved state to be restored. If this parameter is positive, nSavedDC represents a specific instance of the state to be restored. If this parameter is negative, nSavedDC represents an instance relative to the current state. For example, –1 restores the most recently saved state.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The stack can contain the state information for several instances of the DC. If the state specified by the specified parameter is not at the top of the stack, RestoreDC deletes all state information between the top of the stack and the specified instance.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, SaveDC


SaveDC

The SaveDC function saves the current state of the specified device context (DC) by copying data describing selected objects and graphic modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a context stack.

int SaveDC(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the DC whose state is to be saved.

Return Values

If the function succeeds, the return value identifies the saved state.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The SaveDC function can be used any number of times to save any number of instances of the DC state.

A saved state can be restored by using the RestoreDC function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, RestoreDC


SelectObject

The SelectObject function selects an object into the specified device context (DC). The new object replaces the previous object of the same type.

HGDIOBJ SelectObject(
  HDC hdc,          // handle to DC
  HGDIOBJ hgdiobj   // handle to object
);

Parameters

hdc
[in] Handle to the DC.
hgdiobj
[in] Handle to the object to be selected. The specified object must have been created by using one of the following functions.
Object | Functions
Bitmap CreateBitmap, CreateBitmapIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBSection

(Bitmaps can be selected for memory DCs only, and for only one DC at a time.)
Brush | CreateBrushIndirect, CreateDIBPatternBrush, CreateDIBPatternBrushPt, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush
Font | CreateFont, CreateFontIndirect
Pen | CreatePen, CreatePenIndirect
Region | CombineRgn, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect

Return Values

If the selected object is not a region and the function succeeds, the return value is a handle to the object being replaced. If the selected object is a region and the function succeeds, the return value is one of the following values.

Value | Meaning
SIMPLEREGION | Region consists of a single rectangle.
COMPLEXREGION | Region consists of more than one rectangle.
NULLREGION | Region is empty.

If an error occurs and the selected object is not a region, the return value is NULL. Otherwise, it is HGDI_ERROR.

Remarks

This function returns the previously selected object of the specified type. An application should always replace a new object with the original, default object after it has finished drawing with the new object.

An application cannot select a bitmap into more than one DC at a time.

ICM: If the object being selected is a brush or a pen, color management is performed.

For an example, see Setting the Pen or Brush Color.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, CombineRgn, CreateBitmap, CreateBitmapIndirect, CreateBrushIndirect, CreateCompatibleBitmap, CreateDIBitmap, CreateDIBPatternBrush, CreateEllipticRgn, CreateEllipticRgnIndirect, CreateFont, CreateFontIndirect, CreateHatchBrush, CreatePatternBrush, CreatePen, CreatePenIndirect, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateSolidBrush, SelectClipRgn, SelectPalette


SetDCBrushColor

SetDCBrushColor function sets the current device context (DC) brush color to the specified color value. If the device cannot represent the specified color value, the color is set to the nearest physical color.

COLORREF SetDCBrushColor(
  HDC hdc,          // handle to DC
  COLORREF crColor  // new brush color
);

Parameters

hdc
[in] Handle to the DC.
crColor
[in] Specifies the new brush color.

Return Values

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

When the stock DC_BRUSH is selected in a DC, all the subsequent drawings will be done using the DC brush color until the stock brush is deselected. The default DC_BRUSH color is WHITE.

The function returns the previous DC_BRUSH color, even if the stock brush DC_BRUSH is not selected in the DC: however, this will not be used in drawing operations until the stock DC_BRUSH is selected in the DC.

The GetStockObject function with an argument of DC_BRUSH or DC_PEN can be used interchangeably with the SetDCPenColor and SetDCBrushColor functions.

ICM: Color management is performed if ICM is enabled.

For an example of setting colors, see Setting the Pen or Brush Color.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, GetDCBrushColor, COLORREF


SetDCPenColor

SetDCPenColor function sets the current device context (DC) pen color to the specified color value. If the device cannot represent the specified color value, the color is set to the nearest physical color.

COLORREF SetDCPenColor(
  HDC hdc,          // handle to DC
  COLORREF crColor  // new pen color
);

Parameters

hdc
[in] Handle to the DC.
crColor
[in] Specifies the new pen color.

Return Values

If the function succeeds, the return value specifies the previous DC pen color as a COLORREF value. If the function fails, the return value is CLR_INVALID.

Remarks

The function returns the previous DC_PEN color, even if the stock pen DC_PEN is not selected in the DC; however, this will not be used in drawing operations until the stock DC_PEN is selected in the DC.

The GetStockObject function with an argument of DC_BRUSH or DC_PEN can be used interchangeably with the SetDCPenColor and SetDCBrushColor functions.

ICM: Color management is performed if ICM is enabled.

For an example of setting colors, see Setting the Pen or Brush Color.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Device Contexts Overview, Device Context Functions, GetDCPenColor, COLORREF


Device Context Structures

The following structures are used with device contexts.

DISPLAY_DEVICE
VIDEOPARAMETERS


DISPLAY_DEVICE

The DISPLAY_DEVICE structure receives information about the display device specified by the iDevNum parameter of the EnumDisplayDevices function.

typedef struct _DISPLAY_DEVICE {
  DWORD cb;
  WCHAR DeviceName[32];
  WCHAR DeviceString[128];
  DWORD StateFlags;
  WCHAR DeviceID[128];
  WCHAR DeviceKey[128];
} DISPLAY_DEVICE, *PDISPLAY_DEVICE;

Members

cb
Size, in bytes, of the DISPLAY_DEVICE structure. This must be initialized prior to calling EnumDisplayDevices.
DeviceName
An array of characters identifying the device name. This is either the adapter device or the monitor device.
DeviceString
An array of characters containing the device context string. This is either a description of the display adapter or of the display monitor.
StateFlags
Device state flags. It can be any reasonable combination of the following.
Value | Meaning
DISPLAY_DEVICE_ATTACHED_TO_DESKTOP | The device is part of the desktop.
DISPLAY_DEVICE_MIRRORING_DRIVER | Represents a pseudo device used to mirror application drawing for remoting or other purposes. An invisible pseudo monitor is associated with this device. For example, NetMeeting uses it. Note that GetSystemMetrics(SM_MONITORS) only accounts for visible display monitors.
DISPLAY_DEVICE_MODESPRUNED | The device has more display modes than its output devices support.
DISPLAY_DEVICE_PRIMARY_DEVICE | The primary desktop is on the device. For a system with a single display card, this is always set. For a system with multiple display cards, only one device can have this set.
DISPLAY_DEVICE_REMOVABLE | The device is removable; it cannot be the primary display.
DISPLAY_DEVICE_VGA_COMPATIBLE | The device is VGA compatible.

DeviceID
Windows 98/Me: A string that uniquely identifies the hardware adapter or the monitor. This is the Plug and Play identifier.
DeviceKey
Reserved.

Remarks

The four string members are set based on the parameters passed to EnumDisplayDevices. If the lpDevice param is NULL, then DISPLAY_DEVICE is filled in with information about the display adapter(s). If it is a valid device name, then it is filled in with information about the monitor(s) for that device.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Device Contexts Overview, Device Context Structures, EnumDisplayDevices, GetSystemMetrics


VIDEOPARAMETERS

The VIDEOPARAMETERS structure contains information for a video connection.

typedef struct _VIDEOPARAMETERS {
  GUID  guid;
  ULONG  dwOffset;
  ULONG  dwCommand;
  ULONG  dwFlags;
  ULONG  dwMode;
  ULONG  dwTVStandard;
  ULONG  dwAvailableModes;
  ULONG  dwAvailableTVStandard;
  ULONG  dwFlickerFilter;
  ULONG  dwOverScanX;
  ULONG  dwOverScanY;
  ULONG  dwMaxUnscaledX;
  ULONG  dwMaxUnscaledY;
  ULONG  dwPositionX;
  ULONG  dwPositionY;
  ULONG  dwBrightness;
  ULONG  dwContrast;
  ULONG  dwCPType;
  ULONG  dwCPCommand;
  ULONG  dwCPStandard;
  ULONG  dwCPKey;
  ULONG  bCP_APSTriggerBits;
  UCHAR  bOEMCopyProtection[256];
} VIDOEPARAMETERS, *PVIDEOPARAMETERS;

Members

guid
Specifies the GUID for this structure. {02C62061-1097-11d1-920F-00A024DF156E}. Display drivers should verify the GUID at the start of the structure before processing the structure.
dwOffset
Reserved; must be zero.
dwCommand
Specifies whether to retrieve or set the values that are indicated by the other members of this structure. This member can be one of the following values.
Value | Meaning
VP_COMMAND_GET | Gets current video capabilities. If capability is not supported, dwFlags is 0.
VP_COMMAND_SET | Sets video parameters.

dwFlags
Indicates which fields contain valid data. For VP_COMMAND_GET, these are the fields to retrieve, for VP_COMMAND_SET, these are the fields to set. If a capability is not supported, dwFlags is 0. It can be any combination of the following.
Value | Fields containing data
VP_FLAGS_TV_MODE | dwMode
VP_FLAGS_TV_STANDARD | dwTVStandard
VP_FLAGS_FLICKER | dwFlickerFilter
VP_FLAGS_OVERSCAN | dwOverScanX, dwOverScanY
VP_FLAGS_MAX_UNSCALED | dwMaxUnscaledX, dwMaxUnscaledY. Do not use if VP_COMMAND_SET is specified.
VP_FLAGS_POSITION | dwPositionX, dwPositionY
VP_FLAGS_BRIGHTNESS | dwBrightness
VP_FLAGS_CONTRAST | dwContrast
VP_FLAGS_COPYPROTECT | dwCPType, dwCPCommand, dwCPStandard

dwMode
Specifies the current playback mode. This member is valid for both VP_COMMAND_GET and VP_COMMAND_SET. It can be one of the following.
Value | Meaning
VP_MODE_WIN_GRAPHICS | Describes a set of display settings that are optimal for Windows display, with the flicker filter on and any overscan display off.
VP_MODE_TV_PLAYBACK | Describes a set of display settings for video playback, with the flicker filter off and the overscan display on.

dwTVStandard
Specifies the TV standard. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET. It can be any one of the following.
  • VP_TV_STANDARD_NTSC_433
  • VP_TV_STANDARD_NTSC_M
  • VP_TV_STANDARD_NTSC_M_J
  • VP_TV_STANDARD_PAL_60
  • VP_TV_STANDARD_PAL_B
  • VP_TV_STANDARD_PAL_D
  • VP_TV_STANDARD_PAL_G
  • VP_TV_STANDARD_PAL_H
  • VP_TV_STANDARD_PAL_I
  • VP_TV_STANDARD_PAL_M
  • VP_TV_STANDARD_PAL_N
  • VP_TV_STANDARD_SECAM_B
  • VP_TV_STANDARD_SECAM_D
  • VP_TV_STANDARD_SECAM_G
  • VP_TV_STANDARD_SECAM_H
  • VP_TV_STANDARD_SECAM_K
  • VP_TV_STANDARD_SECAM_K1
  • VP_TV_STANDARD_SECAM_L
  • VP_TV_STANDARD_SECAM_L1
  • VP_TV_STANDARD_WIN_VGA
dwAvailableModes
Specifies which modes are available. This is valid only for VP_COMMAND_GET. It can be any combination of the values specified in dwMode.
dwAvailableTVStandard
Specifies the TV standards that are available. This is valid only for VP_COMMAND_GET. It can be any combination of the values specified in dwTVStandard.
dwFlickerFilter
Specifies the flicker reduction provided by the hardware. This is a percentage value in tenths of a percent, from 0 to 1,000, where 0 is no flicker reduction and 1,000 is maximum flicker reduction. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwOverScanX
Specifies the amount of overscan in the horizontal direction. This is a percentage value in tenths of a percent, from 0 to 1,000. A value of 0 indicates no overscan, ensuring that the entire display is visible. A value of 1,000 is maximum overscan and typically causes some of the image to be off the edge of the screen. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwOverScanY
Specifies the amount of overscan in the vertical direction. This is a percentage value in tenths of a percent, from 0 to 1,000. A value of 0 indicates no overscan, ensuring that the entire display is visible. A value of 1,000 is maximum overscan and typically causes some of the image to be off the edge of the screen. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwMaxUnscaledX
Specifies the maximum horizontal resolution, in pixels, that is supported when the video is not scaled. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwMaxUnscaledY
Specifies the maximum vertical resolution, in pixels, that is supported when the video is not scaled. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwPositionX
Specifies the horizontal adjustment to the center of the image. Units are in pixels. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwPositionY
Specifies the vertical adjustment to the center of the image. Units are in scan lines. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwBrightness
Adjustment to the DC offset of the video signal to increase brightness on the television. It is a percentage value, 0 to 100, where 0 means no adjustment and 100 means maximum adjustment. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwContrast
Adjustment to the gain of the video signal to increase the intensity of whiteness on the television. It is a percentage value, 0 to 100, where 0 means no adjustment and 100 means maximum adjustment. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.
dwCPType
Specifies the copy protection type. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET. It can be one of the following.
Value | Meaning
VP_CP_TYPE_APS_TRIGGER | Only DVD trigger bits available.
VP_CP_TYPE_MACROVISION | Full Macrovision data is available.

dwCPCommand
Specifies the copy protection command. This field is only valid for VP_COMMAND_SET. It can be one of the following.
Value | Meaning
VP_CP_CMD_ACTIVATE | Activate copy protection.
VP_CP_CMD_CHANGE | Change copy protection.
VP_CP_CMD_DEACTIVATE | Deactivate copy protection.

dwCPStandard
Specifies TV standards for which copy protection types are available. This field is valid only for VP_COMMAND_GET.
dwCPKey
Specifies the copy protection key returned if dwCPCommand is set to VP_CP_CMD_ACTIVATE. The caller must set this key when the dwCPCommand field is either VP_CP_CMD_DEACTIVATE or VP_CP_CMD_CHANGE. If the caller sets an incorrect key, the driver must not change the current copy protection settings. This field is valid only for VP_COMMAND_SET.
bCP_APSTriggerBits
Specifies the DVD APS trigger bit flag. This is valid only for VP_COMMAND_SET. Currently, only bits 0 and 1 are valid. It can be one of the following.
Value | Meaning
0 | No copy protection.
1, 2, or 3 | Macrovision-defined analog protection methods.

bOEMCopyProtection
Specifies the OEM-specific copy protection data. Maximum of 256 characters. This field is valid for both VP_COMMAND_GET and VP_COMMAND_SET.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Tvout.h; include Windows.h.

See Also

Device Contexts Overview, Device Context Structures, ChangeDisplaySettingsEx


Device Context Messages

The following message is used with device contexts.

WM_DEVMODECHANGE


WM_DEVMODECHANGE

The WM_DEVMODECHANGE message is sent to all top-level windows whenever the user changes device-mode settings.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DEVMODECHANGE
  WPARAM wParam,   // not used
  LPARAM lParam    // device name (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a string that specifies the device name.

Return Values

An application should return zero if it processes this message.

Remarks

This message cannot be sent directly to a window. To send the WM_DEVMODECHANGE message to all top-level windows, use the SendMessageTimeout function with the hWnd parameter set to HWND_BROADCAST.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Device Contexts Overview, Device Context Messages


Filled Shapes

Filled shapes are geometric forms that are outlined by using the current pen and filled by using the current brush. There are five filled shapes:

  • Ellipse
  • Chord
  • Pie
  • Polygon
  • Rectangle

This overview describes the filled shapes.

  • About Filled Shapes
  • Using Filled Shapes
  • Filled Shape Reference


About Filled Shapes

A Win32®-based application uses filled shapes in a variety of ways. Spreadsheet applications, for example, use filled shapes to construct charts and graphs, and drawing and painting applications use filled shapes to allow the user to draw figures and illustrations.

  • Ellipse
  • Chord
  • Pie
  • Polygon
  • Rectangle


About Ellipses

An ellipse is a closed curve defined by two fixed points (f1 and f2) such that the sum of the distances (d1 + d2) from any point on the curve to the two fixed points is constant. The following illustration shows an ellipse drawn by using the Ellipse function.

When calling Ellipse, an application supplies the coordinates of the upper-left and lower-right corners of the ellipse's bounding rectangle. A bounding rectangle is the smallest rectangle completely surrounding the ellipse. When the system draws the ellipse, it excludes the right and lower sides if no world transformations are set. Therefore, for any rectangle measuring x units wide by y units high, the associated ellipse measures x–1 units wide by y–1 units high. If the application sets a world transformation by calling the SetWorldTransform or ModifyWorldTransform function, the system includes the right and lower sides.


About Chords

A chord is a region bounded by the intersection of an ellipse and a line segment called a secant. The following illustration shows a chord drawn by using the Chord function.

When calling Chord, an application supplies the coordinates of the upper-left and lower-right corners of the ellipse's bounding rectangle, as well as the coordinates of two points defining two radials. A radial is a line drawn from the center of an ellipse's bounding rectangle to a point on the ellipse.

When the system draws the curved part of the chord, it does so by using the current arc direction for the specified device context. The default arc direction is counterclockwise. You can have your application reset the arc direction by calling the SetArcDirection function.


About Pies

A pie is a region bounded by the intersection of an ellipse curve and two radials. The following illustration shows a pie drawn by using the Pie function.

When calling Pie, an application supplies the coordinates of the upper-left and lower-right corners of the ellipse's bounding rectangle, as well as the coordinates of two points defining two radials.

When the system draws the curved part of the pie, it uses the current arc direction for the given device context. The default arc direction is counterclockwise. An application can reset the arc direction by calling the SetArcDirection function.


About Polygons

A polygon is a filled shape with straight sides. The sides of a polygon are drawn by using the current pen. When the system fills a polygon, it uses the current brush and the current polygon fill mode. The two fill modes—alternate (the default) and winding—determine whether regions within a complex polygon are filled or left unpainted. An application can select either mode by calling the SetPolyFillMode function. For more information about polygon fill modes, see Regions.

The following illustration shows a polygon drawn by using Polygon.

In addition to drawing a single polygon by using Polygon, an application can draw multiple polygons by using the PolyPolygon function.


Drawing Rectangles

A rectangle is a four-sided polygon whose opposing sides are parallel and equal in length. Although an application can draw a rectangle by calling the Polygon function, supplying the coordinates of each corner, the Rectangle function provides a simpler method. This function requires only the coordinates for the upper-left and the lower-right corners. When an application calls the Rectangle function, the system draws the rectangle, excluding the right and lower sides if no world transformation is set for the given device context.

If a world transformation has been set by using the SetWorldTransform or ModifyWorldTransform function, the system includes the right and lower edges.

In addition to drawing a traditional rectangle, you can draw rectangles with rounded corners. The RoundRect function requires that the application supply the coordinates of the lower-left and upper-right corners, as well as the width and height of the ellipse used to round each corner.

The Microsoft® Win32® API also provides three functions that applications can use to manipulate rectangles, described as follows.

Function | Description
FillRect | Repaints the interior of a rectangle.
FrameRect | Redraws the sides of a rectangle.
InvertRect | Inverts the colors that appear within the interior of a rectangle.


Using Filled Shapes

This section illustrates how to use filled shape functions. The example uses the main window procedure from an application that enables the user to draw ellipses, rectangles, and rectangles with rounded corners.

The user draws a filled shape by selecting a particular shape from the menu, positioning the cursor at the upper-left corner of the shape (or the shape's bounding rectangle in the case of an ellipse), and then dragging the mouse until the desired dimensions are obtained.

The following illustration shows three filled shapes drawn using the sample code in this section.

To enable the user to draw filled shapes, include the following popup menu in your application.

   POPUP "Filled &Shapes"
   {
      MENUITEM "&Ellipse",   IDM_ELLIPSE
      MENUITEM "&Rectangle", IDM_RECTANGLE
      MENUITEM "R&oundRect", IDM_ROUNDRECT
   }

The menu item values in the menu template are constants that you must define as follows in your application's header file.

#define IDM_ELLIPSE    1100
#define IDM_RECTANGLE  1200
#define IDM_ROUNDRECT  1300

Finally, include the following window procedure in your application.

BOOL CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam,
                          LPARAM lParam)
{
    HDC hdc;          // handle to device context (DC)
    PAINTSTRUCT ps;   // paint data for Begin/EndPaint
    POINT ptClientUL; // client area upper left corner
    POINT ptClientLR; // client area lower right corner
    static HDC hdcCompat; // handle to DC for bitmap
    static POINT pt;      // x- and y-coordinates of cursor
    static RECT rcTarget; // rect to receive filled shape
    static RECT rcClient; // client area rectangle
    static BOOL fSizeEllipse; // TRUE if ellipse is sized
    static BOOL fDrawEllipse;   // TRUE if ellipse is drawn
    static BOOL fDrawRectangle; // TRUE if rectangle is drawn
    static BOOL fSizeRectangle; // TRUE if rectangle is sized
    static BOOL fSizeRoundRect; // TRUE if rounded rect is sized
    static BOOL fDrawRoundRect; // TRUE if rounded rect is drawn
    static int nEllipseWidth;   // width for round corners
    static int nEllipseHeight;  // height for round corners

    switch (uMsg)
    {
        case WM_COMMAND:
            switch (wParam)
            {

                // Set the appropriate flag to indicate which
                // filled shape the user is drawing.

                case IDM_ELLIPSE:
                    fSizeEllipse = TRUE;
                break;

                case IDM_RECTANGLE:
                    fSizeRectangle = TRUE;
                break;

                case IDM_ROUNDRECT:
                    fSizeRoundRect = TRUE;
                break;

                default:
                    return DefWindowProc(hwnd, uMsg, wParam,
                         lParam);
            }
            break;

        case WM_CREATE:
            nEllipseWidth = 20;
            nEllipseHeight = 20;

            return 0;

        case WM_PAINT:

            BeginPaint(hwnd, &ps);

            // Because the default brush is white, select
            // a different brush into the device context
            // to demonstrate the painting of filled shapes.

            SelectObject(ps.hdc, GetStockObject(GRAY_BRUSH));

            // If one of the filled shape "draw" flags is TRUE,
            // draw the corresponding shape.

            if (fDrawEllipse)
            {
                Ellipse(ps.hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom);
                fDrawEllipse = FALSE;
                rcTarget.left = rcTarget.right = 0;
                rcTarget.top = rcTarget.bottom = 0;
            }

            if (fDrawRectangle)
            {
                Rectangle(ps.hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom);
                fDrawRectangle = FALSE;
                rcTarget.left = rcTarget.right = 0;
                rcTarget.top = rcTarget.bottom = 0;
            }

            if (fDrawRoundRect)
            {
                RoundRect(ps.hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom,
                    nEllipseWidth, nEllipseHeight);
                fDrawRectangle = FALSE;
                rcTarget.left = rcTarget.right = 0;
                rcTarget.top = rcTarget.bottom = 0;
            }

            EndPaint(hwnd, &ps);
            break;

        case WM_SIZE:

            // Convert the client coordinates of the client area
            // rectangle to screen coordinates and save them in a
            // rectangle. The rectangle is passed to the ClipCursor
            // function during WM_LBUTTONDOWN processing.

            GetClientRect(hwnd, &rcClient);
            ptClientUL.x = rcClient.left;
            ptClientUL.y = rcClient.top;
            ptClientLR.x = rcClient.right;
            ptClientLR.y = rcClient.bottom;
            ClientToScreen(hwnd, &ptClientUL);
            ClientToScreen(hwnd, &ptClientLR);
            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,
                ptClientLR.x, ptClientLR.y);
            return 0;

        case WM_LBUTTONDOWN:

            // Restrict the cursor to the client area.
            // This ensures that the window receives a matching
            // WM_LBUTTONUP message.

            ClipCursor(&rcClient);

            // Save the coordinates of the cursor.

            pt.x = (LONG) LOWORD(lParam);
            pt.y = (LONG) HIWORD(lParam);

            // If the user chooses one of the filled shapes,
            // set the appropriate flag to indicate that the
            // shape is being sized.

             if (fDrawEllipse)
                fSizeEllipse = TRUE;

            return 0;

        case WM_MOUSEMOVE:

            // If one of the "size" flags is set, draw
            // the target rectangle as the user drags
            // the mouse.

            if ((wParam && MK_LBUTTON)
                    && (fSizeEllipse || fSizeRectangle
                    || fSizeRoundRect))
            {

                // Set the mixing mode so that the pen color is the
                // inverse of the background color. The previous
                // rectangle can then be erased by drawing
                // another rectangle on top of it.

                hdc = GetDC(hwnd);
                SetROP2(hdc, R2_NOTXORPEN);

                // If a previous target rectangle exists, erase
                // it by drawing another rectangle on top.

                if (!IsRectEmpty(&rcTarget))
                {
                    Rectangle(hdc, rcTarget.left, rcTarget.top,
                        rcTarget.right, rcTarget.bottom);
                }

                // Save the coordinates of the target rectangle.
                // Avoid invalid rectangles by ensuring that the
                // value of the left coordinate is greater than
                // that of the right, and that the value of the
                // bottom coordinate is greater than that of
                // the top.

                if ((pt.x < (LONG) LOWORD(lParam)) &&
                        (pt.y > (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, pt.x, HIWORD(lParam),
                        LOWORD(lParam), pt.y);
                }

                else if ((pt.x > (LONG) LOWORD(lParam)) &&
                        (pt.y > (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, LOWORD(lParam),
                        HIWORD(lParam), pt.x, pt.y);
                }

                else if ((pt.x > (LONG) LOWORD(lParam)) &&
                        (pt.y < (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, LOWORD(lParam), pt.y,
                        pt.x, HIWORD(lParam));
                }
                else
                {
                    SetRect(&rcTarget, pt.x, pt.y, LOWORD(lParam),
                        HIWORD(lParam));
                }

                // Draw the new target rectangle.

                Rectangle(hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom);
                ReleaseDC(hwnd, hdc);
            }
            return 0;

        case WM_LBUTTONUP:

            // If one of the "size" flags is TRUE, reset it to FALSE,
            // and then set the corresponding "draw" flag. Invalidate
            // the appropriate rectangle and issue a WM_PAINT message.

            if (fSizeEllipse)
            {
                fSizeEllipse = FALSE;
                fDrawEllipse = TRUE;
            }

            if (fSizeRectangle)
            {
                fSizeRectangle = FALSE;
                fDrawRectangle = TRUE;
            }

            if (fSizeRoundRect)
            {
                fSizeRoundRect = FALSE;
                fDrawRoundRect = TRUE;
            }

            if (fDrawEllipse || fDrawRectangle || fDrawRoundRect)
            {
                InvalidateRect(hwnd, &rcTarget, TRUE);
                UpdateWindow(hwnd);
            }

            // Release the cursor.

            ClipCursor((LPRECT) NULL);
            return 0;

        case WM_DESTROY:

            // Destroy the background brush, compatible bitmap,
            // and bitmap.

            DeleteDC(hdcCompat);
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return (LRESULT) NULL;
}


Filled Shape Reference

The following elements are used with filled shapes:

  • Filled Shape Functions


Filled Shape Functions

The following functions are used with filled shapes.

Function | Description
Chord | Draws an area bounded by an ellipse and a line segment.
Ellipse | Draws an ellipse.
FillRect | Fills a rectangle using a brush.
FrameRect | Draws a border around a rectangle using a brush.
InvertRect | Inverts the color values of the pixels in a rectangle.
Pie | Draws a pie-shaped wedge bounded by an ellipse and two radials.
Polygon | Draws a polygon.
PolyPolygon | draws a series of closed polygons.
Rectangle | Draws a rectangle.
RoundRect | Draws a rectangle with rounded corners.


Chord

The Chord function draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a secant). The chord is outlined by using the current pen and filled by using the current brush.

BOOL Chord(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner of rectangle
  int nTopRect,    // y-coord of upper-left corner of rectangle
  int nRightRect,  // x-coord of lower-right corner of rectangle
  int nBottomRect, // y-coord of lower-right corner of rectangle
  int nXRadial1,   // x-coord of first radial's endpoint
  int nYRadial1,   // y-coord of first radial's endpoint
  int nXRadial2,   // x-coord of second radial's endpoint
  int nYRadial2    // y-coord of second radial's endpoint
);

Parameters

hdc
[in] Handle to the device context in which the chord appears.
nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the bounding rectangle.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the bounding rectangle.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the bounding rectangle.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the bounding rectangle.
nXRadial1
[in] Specifies the x-coordinate of the endpoint of the radial defining the beginning of the chord.
nYRadial1
[in] Specifies the y-coordinate of the endpoint of the radial defining the beginning of the chord.
nXRadial2
[in] Specifies the x-coordinate of the endpoint of the radial defining the end of the chord.
nYRadial2
[in] Specifies the y-coordinate of the endpoint of the radial defining the end of the chord.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point where the ellipse intersects the second radial. The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

If the starting point and ending point of the curve are the same, a complete ellipse is drawn.

The current position is neither used nor updated by Chord.

Windows 95/98/Me: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, AngleArc, Arc, ArcTo, Pie


Ellipse

The Ellipse function draws an ellipse. The center of the ellipse is the center of the specified bounding rectangle. The ellipse is outlined by using the current pen and is filled by using the current brush.

BOOL Ellipse(
  HDC hdc,        // handle to DC
  int nLeftRect,  // x-coord of upper-left corner of rectangle
  int nTopRect,   // y-coord of upper-left corner of rectangle
  int nRightRect, // x-coord of lower-right corner of rectangle
  int nBottomRect // y-coord of lower-right corner of rectangle
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the bounding rectangle.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the bounding rectangle.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the bounding rectangle.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the bounding rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The current position is neither used nor updated by Ellipse.

Windows 95/98/Me: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

For an example, see Using Filled Shapes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, Arc, ArcTo


FillRect

The FillRect function fills a rectangle by using the specified brush. This function includes the left and top borders, but excludes the right and bottom borders of the rectangle.

int FillRect(
  HDC hDC,           // handle to DC
  CONST RECT *lprc,  // rectangle
  HBRUSH hbr         // handle to brush
);

Parameters

hDC
[in] Handle to the device context.
lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the rectangle to be filled.
hbr
[in] Handle to the brush used to fill the rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The brush identified by the hbr parameter may be either a handle to a logical brush or a color value. If specifying a handle to a logical brush, call one of the following functions to obtain the handle: CreateHatchBrush, CreatePatternBrush, or CreateSolidBrush. Additionally, you may retrieve a handle to one of the stock brushes by using the GetStockObject function. If specifying a color value for the hbr parameter, it must be one of the standard system colors (the value 1 must be added to the chosen color). For example:

FillRect(hdc, &rect, (HBRUSH) (COLOR_WINDOW+1));

For a list of all the standard system colors, see GetSysColor.

When filling the specified rectangle, FillRect does not include the rectangle's right and bottom sides. GDI fills a rectangle up to, but not including, the right column and bottom row, regardless of the current mapping mode.

For an example, see Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, GetStockObject, RECT


FrameRect

The FrameRect function draws a border around the specified rectangle by using the specified brush. The width and height of the border are always one logical unit.

int FrameRect(
  HDC hDC,           // handle to DC
  CONST RECT *lprc,  // rectangle
  HBRUSH hbr         // handle to brush
);

Parameters

hDC
[in] Handle to the device context in which the border is drawn.
lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the upper-left and lower-right corners of the rectangle.
hbr
[in] Handle to the brush used to draw the border.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The brush identified by the hbr parameter must have been created by using the CreateHatchBrush, CreatePatternBrush, or CreateSolidBrush function, or retrieved by using the GetStockObject function.

If the bottom member of the RECT structure is less than or equal to the top member, or if the right member is less than or equal to the left member, the function does not draw the rectangle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, GetStockObject, RECT


InvertRect

The InvertRect function inverts a rectangle in a window by performing a logical NOT operation on the color values for each pixel in the rectangle's interior.

BOOL InvertRect(
  HDC hDC,           // handle to DC
  CONST RECT *lprc   // rectangle
);

Parameters

hDC
[in] Handle to the device context.
lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the rectangle to be inverted.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

On monochrome screens, InvertRect makes white pixels black and black pixels white. On color screens, the inversion depends on how colors are generated for the screen. Calling InvertRect twice for the same rectangle restores the display to its previous colors.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, FillRect, RECT


Pie

The Pie function draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined by using the current pen and filled by using the current brush.

BOOL Pie(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner of rectangle
  int nTopRect,    // y-coord of upper-left corner of rectangle
  int nRightRect,  // x-coord of lower-right corner of rectangle
  int nBottomRect, // y-coord of lower-right corner of rectangle
  int nXRadial1,   // x-coord of first radial's endpoint
  int nYRadial1,   // y-coord of first radial's endpoint
  int nXRadial2,   // x-coord of second radial's endpoint
  int nYRadial2    // y-coord of second radial's endpoint
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the bounding rectangle.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the bounding rectangle.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the bounding rectangle.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the bounding rectangle.
nXRadial1
[in] Specifies the x-coordinate of the endpoint of the first radial.
nYRadial1
[in] Specifies the y-coordinate of the endpoint of the first radial.
nXRadial2
[in] Specifies the x-coordinate of the endpoint of the second radial.
nYRadial2
[in] Specifies the y-coordinate of the endpoint of the second radial.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point where the ellipse intersects the second radial.

The current position is neither used nor updated by the Pie function.

Windows 95/98/Me: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, AngleArc, Arc, ArcTo, Chord


Polygon

The Polygon function draws a polygon consisting of two or more vertices connected by straight lines. The polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode.

BOOL Polygon(
  HDC hdc,                // handle to DC
  CONST POINT *lpPoints,  // polygon vertices
  int nCount              // count of polygon vertices
);

Parameters

hdc
[in] Handle to the device context.
lpPoints
[in] Pointer to an array of POINT structures that specify the vertices of the polygon.
nCount
[in] Specifies the number of vertices in the array. This value must be greater than or equal to 2.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The polygon is closed automatically by drawing a line from the last vertex to the first.

The current position is neither used nor updated by the Polygon function.

Windows 95/98/Me: Polygon is limited in the number of points it can draw, depending on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum number of points
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but the device does not support wideline | approximately 1360 (that is, a few less than 16K / 12)

Any extra points are ignored. To draw a line with more points, divide your data into groups, each of which have less than the maximum number of points, and call the function for each group of points. Remember to connect the line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, GetPolyFillMode, POINT, Polyline, PolylineTo, PolyPolygon, SetPolyFillMode


PolyPolygon

The PolyPolygon function draws a series of closed polygons. Each polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode. The polygons drawn by this function can overlap.

BOOL PolyPolygon(
  HDC hdc,                  // handle to DC
  CONST POINT *lpPoints,    // array of vertices
  CONST INT *lpPolyCounts,  // array of count of vertices
  int nCount                // count of polygons
);

Parameters

hdc
[in] Handle to the device context.
lpPoints
[in] Pointer to an array of POINT structures that define the vertices of the polygons. The polygons are specified consecutively. Each polygon is closed automatically by drawing a line from the last vertex to the first. Each vertex should be specified once.
lpPolyCounts
[in] Pointer to an array of integers, each of which specifies the number of points in the corresponding polygon. Each integer must be greater than or equal to 2.
nCount
[in] Specifies the total number of polygons.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The current position is neither used nor updated by this function.

Windows 95/98/Me: Polypolygon is limited in the number of points it can draw, depending on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum number of points
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but the device does not support wideline | approximately 1360 (that is, a few less than 16K / 12)

Any extra points are ignored. To draw the polygons with more points, divide your data into groups, each of which have less than the maximum number of points, and call the function for each group of points. Note, it is best to have a polygon in only one of the groups.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, GetPolyFillMode, POINT, Polygon, Polyline, PolylineTo, SetPolyFillMode


Rectangle

The Rectangle function draws a rectangle. The rectangle is outlined by using the current pen and filled by using the current brush.

BOOL Rectangle(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner of rectangle
  int nTopRect,    // y-coord of upper-left corner of rectangle
  int nRightRect,  // x-coord of lower-right corner of rectangle
  int nBottomRect  // y-coord of lower-right corner of rectangle
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the logical x-coordinate of the upper-left corner of the rectangle.
nTopRect
[in] Specifies the logical y-coordinate of the upper-left corner of the rectangle.
nRightRect
[in] Specifies the logical x-coordinate of the lower-right corner of the rectangle.
nBottomRect
[in] Specifies the logical y-coordinate of the lower-right corner of the rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The current position is neither used nor updated by Rectangle.

The rectangle that is drawn excludes the bottom and right edges.

If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less in height and 1 pixel less in width.

For an example, see Using Filled Shapes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, RoundRect


RoundRect

The RoundRect function draws a rectangle with rounded corners. The rectangle is outlined by using the current pen and filled by using the current brush.

BOOL RoundRect(
  HDC hdc,         // handle to DC
  int nLeftRect,   // x-coord of upper-left corner of rectangle
  int nTopRect,    // y-coord of upper-left corner of rectangle
  int nRightRect,  // x-coord of lower-right corner of rectangle
  int nBottomRect, // y-coord of lower-right corner of rectangle
  int nWidth,      // width of ellipse
  int nHeight      // height of ellipse
);

Parameters

hdc
[in] Handle to the device context.
nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the rectangle.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the rectangle.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the rectangle.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the rectangle.
nWidth
[in] Specifies the width of the ellipse used to draw the rounded corners.
nHeight
[in] Specifies the height of the ellipse used to draw the rounded corners.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The current position is neither used nor updated by this function.

Windows 95/98/Me: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

For an example, see Using Filled Shapes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Filled Shapes Overview, Filled Shape Functions, Rectangle


Fonts and Text

Fonts are used to draw text on video displays and other output devices. The Microsoft® Win32® API provides a set of functions you can use to install, select, and query different fonts.

  • About Fonts
  • About Text Output
  • Using the Font and Text-Output Functions
  • Font and Text Reference


About Fonts

To a person trained in the mechanics of manuscript composition or familiar with standard typography, some of the typographic terms used in this overview may be unusual. Most of the differences between standard typography and Microsoft® Windows® operating system fonts and text reflect changes in technology. The original typographic terms were based on hot-metal composition, whereas the terms used here, which appear as member names for the font and text output structures, reflect a new technology based on laser-printer output and composition performed on a personal computer using desktop publishing software.

The following sections discuss fonts:

  • Font Elements
  • Font Families
  • Raster, Vector, TrueType, and OpenType Fonts
  • Character Sets Used by Fonts
  • Font Installation and Deletion
  • Fonts from Multiple Resource Files
  • Font Creation and Selection
  • Embedded Fonts


Font Elements

A font is a collection of characters and symbols that share a common design. The three major elements of this design are referred to as typeface, style, and size.

Typeface

The term typeface refers to specific characteristics of characters and symbols in the font, such as the width of the thick and thin strokes that compose the characters and the presence or absence of serifs. A serif is the short cross line at the ends of an unconnected stroke. A font or typeface without serifs is usually called a sans-serif font.

Style

The term style refers to the weight and slant of a font. Font weights can range from thin to black. The following is a list of possible weights for fonts (from lightest to heaviest):

Thin
Extralight
Light
Normal
Medium
Semibold
Bold
Extrabold
Heavy

Three terms categorize the slant of a font: roman, oblique, and italic.

The characters in a roman font are upright. The characters in an oblique font are artificially slanted. The slant is achieved by performing a shear transformation on the characters from a roman font. The characters in an italic font are truly slanted and appear as they were designed. For more information on shearing, see Coordinate Spaces and Transformations.

Size

The size of a font is an imprecise value. It can generally be determined by measuring the distance from the bottom of a lowercase g to the top of an adjacent uppercase M, as shown in the following illustration.

A font's size is specified in units called points. A point is .013837 of an inch. Following the point system devised by Pierre Simon Fournier, it is common practice to approximate a point as 1/72 inch.


Font Families

A font family is a set of fonts having common stroke width and serif characteristics. There are five font families. A sixth family allows an application to use the default font. The following table describes the font-families.

Font family | Description
Decorative | Specifies a novelty font. An example is Old English.
Dontcare | Specifies a generic family name. This name is used when information about a font does not exist or does not matter. The default font is used.
Modern | Specifies a monospace font with or without serifs. Monospace fonts are usually modern; examples include Pica, Elite, and Courier New.
Roman | Specifies a proportional font with serifs. An example is Times New Roman.
Script | Specifies a font that is designed to look like handwriting; examples include Script and Cursive.
Swiss | Specifies a proportional font without serifs. An example is Arial.

These font families correspond to constants found in the Wingdi.h file: FF_DECORATIVE, FF_DONTCARE, FF_MODERN, FF_ROMAN, FF_SCRIPT, and FF_SWISS. An application uses these constants when it creates a font, selects a font, or retrieves information about a font.

Fonts within a family are distinguished by size (10 point, 24 point, and so on) and style (regular, italic, and so on).


Raster, Vector, TrueType, and OpenType Fonts

Win32-based applications can use four different kinds of font technologies to display and print text:

  • Raster
  • Vector
  • TrueType
  • Microsoft® OpenType®

The differences between these fonts reflect the way that the glyph for each character or symbol is stored in the respective font-resource file:

  • In raster fonts, a glyph is a bitmap that the system uses to draw a single character or symbol in the font.
  • In vector fonts, a glyph is a collection of line endpoints that define the line segments that the system uses to draw a character or symbol in the font.
  • In TrueType and OpenType fonts, a glyph is a collection of line and curve commands as well as a collection of hints.

The system uses the line and curve commands to define the outline of the bitmap for a character or symbol in the TrueType or Microsoft OpenType® font. The system uses the hints to adjust the length of the lines and shapes of the curves used to draw the character or symbol. These hints and the respective adjustments are based on the amount of scaling used to reduce or increase the size of the bitmap. An OpenType font is equivalent to a TrueType font except that an OpenType font allows PostScript glyph definitions in addition to TrueType glyph definitions.

Because the bitmaps for each glyph in a raster font are designed for a specific resolution of device, raster fonts are generally considered to be device dependent. Vector fonts, on the other hand, are not device dependent, because each glyph is stored as a collection of scalable lines. However, vector fonts are generally drawn more slowly than raster or TrueType and OpenType fonts. TrueType and OpenType fonts provide both relatively fast drawing speed and true device independence. By using the hints associated with a glyph, a developer can scale the characters from a TrueType or OpenType font up or down and still maintain their original shape.

As previously mentioned, the glyphs for a font are stored in a font-resource file. A font-resource file is actually a .dll that contains only data—there is no code. For raster and vector fonts, this data is divided into two parts: a header describing the font's metrics and the glyph data. A font-resource file for a raster or vector font is identified by the .fon file name extension. For TrueType and OpenType fonts, there are two files for each font: the first file contains a relatively short header and the second contains the actual font data. The first file is identified by an .fot extension and the second is identified by a .ttf extension.


Character Sets Used by Fonts

All fonts use a character set. A character set contains punctuation marks, numerals, uppercase and lowercase letters, and all other printable characters. Each element of a character set is identified by a number.

Most character sets in use are supersets of the U.S. ASCII character set, which defines characters for the 96 numeric values from 32 through 127. There are five major groups of character sets:

  • Microsoft® Windows®
  • Unicode
  • OEM (original equipment manufacturer)
  • Symbol
  • Vendor-specific

Windows Character Set

The Windows character set is the most commonly used character set in Win32 programming. It is essentially equivalent to the ANSI character set. The blank character is the first character in the Windows character set. It has a hexadecimal value of 0x20 (decimal 32). The last character in the Windows character set has a hexadecimal value of 0xFF (decimal 255).

Many fonts specify a default character. Whenever a request is made for a character that is not in the font, the system provides this default character. Many fonts using the Windows character set specify the period (.) as the default character. TrueType and OpenType fonts typically use an open box as the default character.

Fonts use a break character called a quad to separate words and justify text. Most fonts using the Windows character set specify that the blank character will serve as the break character.

Microsoft Windows version 3.1 added 24 characters to the Windows code page, as shown in the following table.

Character | Name | Windows character code
‚ | Base line single quote | 130
ƒ | Florin | 131
„ | Base line double quote | 132
… | Ellipsis | 133
† | Dagger | 134
‡ | Double dagger | 135
ˆ | Circumflex | 136
‰ | Permille | 137
Š | S Hacek | 138
‹ | Left single guillemet | 139
Œ | OE ligature | 140
' | Left single quote | 145
' | Right single quote | 146
" | Left double quote | 147
" | Right double quote | 148
· | Bullet | 149
– | En dash | 150
— | Em dash | 151
˜ | Tilde | 152
™ | Trademark ligature | 153
š | s Hacek | 154
› | Right single guillemet | 155
œ | oe ligature | 156
Ÿ | Y Dieresis | 159

It should be noted that the characters for left and right single quotes were first added to the character set for the release of Windows 3.0.

Unicode Character Set

The Windows character set uses 8 bits to represent each character; therefore, the maximum number of characters that can be expressed using 8 bits is 256 (2^8). This is usually sufficient for Western languages, including the diacritical marks used in French, German, Spanish, and other languages. However, Eastern languages employ thousands of separate characters, which cannot be encoded by using a single-byte coding scheme. With the proliferation of computer commerce, double-byte coding schemes were developed so that characters could be represented in 8-bit, 16-bit, 24-bit, or 32-bit sequences. This requires complicated passing algorithms; even so, using different code sets could yield entirely different results on two different computers.

To address the problem of multiple coding schemes, the Unicode standard for data representation was developed. A 16-bit character coding scheme, Unicode can represent 65,536 (2^16) characters, which is enough to include all languages in computer commerce today, as well as punctuation marks, mathematical symbols, and room for future expansion. Unicode establishes a unique code for every character to ensure that character translation is always accurate.

OEM Character Set

The OEM character set is typically used in full-screen MS-DOS® sessions for screen display. Characters 32 through 127 are usually the same in the OEM, U.S. ASCII, and Windows character sets. The other characters in the OEM character set (0 through 31 and 128 through 255) correspond to the characters that can be displayed in a full-screen MS-DOS session. These characters are generally different from the Windows characters.

Symbol Character Set

The Symbol character set contains special characters typically used to represent mathematical and scientific formulas.

Vendor-Specific Character Sets

Many printers and other output devices provide fonts based on character sets that differ from the Windows and OEM sets—for example, the Extended Binary Coded Decimal Interchange Code (EBCDIC) character set. To use one of these character sets, the printer driver translates from the Windows character set to the vendor-specific character set.


Font Installation and Deletion

An application can use a font to draw text only if that font is either resident on a specified device or installed in the system font table. The font table is an internal array that identifies all nondevice fonts that are available to a Win32-based application. An application can retrieve the names of fonts currently installed on a device or stored in the internal font table by calling the EnumFontFamilies or ChooseFont functions.

To temporarily install a font, call AddFontResource or AddFontResourceEx. These functions load a font that is stored in a font-resource file. However, this is a temporary installation because after a reboot the font will not be present.

To install a font that will remain after the system is rebooted, use one of the following methods:

  • Go to the Control Panel, click on the Fonts icon, and select "Install New Fonts" from the File menu. The font is available to an application even before the reboot. However, in a terminal server situation the font is available for the current session but is not available for other sessions until after a reboot.
  • Copy the font into the %windir%\fonts folder. Then, either go to the Control Panel and click on the Fonts icon, or call AddFontResource or AddFontResourceEx. The font is available to an application even before the reboot. However, in a terminal server situation the font is available for the current session but is not available for other sessions until after a reboot. If you only copy the font into the %windir%\fonts folder, the font will be available only after the system is rebooted.

In the case of TrueType and OpenType fonts, an additional step is sometimes necessary before the font can be installed in the font table. Some font manufacturers ship only the TrueType or OpenType font-data files (identified by the .ttf extension). Before The system can load these fonts, it requires a corresponding header file (identified by the .fot extension). To create this header file, an application must call the CreateScalableFontResource function and pass the name of the font-data file as the third parameter. When this header file is created, an application can install the font by calling the AddFontResource or AddFontResourceEx function and passing the name of the new header file. For an application that installs TrueType fonts, see the Font Installation SDK at http://fontweb/tools/install/.

When an application finishes using an installed font, it must remove that font by calling the RemoveFontResource function.

Whenever an application calls the functions that add and delete font resources, it should also call the SendMessage function and send a WM_FONTCHANGE message to all top-level windows in the system. This message notifies other applications that the internal font table has been altered by an application that added or removed a font.


Fonts from Multiple Resource Files

Typically, a font is contained in a single font–resource file. However, the information for some fonts is spread among several files. For example, Type 1 multiple master fonts require two files:

  • .pfm for the font metrics
  • .pfb for the font bits

To add a font from multiple files to the system, use the AddFontResource or AddFontResourceEx functions. The lpszFilename parameter in these functions must point to a string that contains the file names separated by the vertical bar or pipe ( | ). For example, to specify abcxxxxx.pfm and abcxxxxx.pfb for a Type 1 font, use the string "abcxxxxx.pfm | abcxxxxx.pfb."

AddFontResourceEx differs from AddFontResource in that the application calling AddFontResourceEx can specify the font as private to itself or non-enumerable.

To add a font from a memory image, use AddFontMemResourceEx. This allows an application to use a font that is embedded in a document or a Web page.

To remove a font that came from multiple resource files, call RemoveFontResource or RemoveFontResourceEx, depending on the function used to add the font. You must specify the same flags that were used to add the font. To remove a font that was added from a memory image, use RemoveFontMemResourceEx.

Using a font that comes from multiple font-resource files is identical to using a font from a single resource file.


Font Creation and Selection

The Font common dialog box simplifies the process of creating and selecting fonts. By initializing the CHOOSEFONT structure and calling the ChooseFont function, an application can support the same font-selection interface that previously required many lines of custom code. (For more information about the Font common dialog box, see Common Dialog Box Library.)

Selection by the User

Most font creation and selection operations involve the user. For example, word processing applications let the user select unique fonts for headings, footnotes, and body text. After the user selects a font by using the Font dialog box and presses the OK button, the ChooseFont function initializes the members of a LOGFONT structure with the attributes of the requested font. To use this font for text-output operations, an application must first create a logical font and then select that font into its device context. A logical font is an application-supplied description of an ideal font. A developer can create a logical font by calling the CreateFont or the CreateFontIndirect functions. In this case, the application would call CreateFontIndirect and supply a pointer to the LOGFONT structure initialized by ChooseFont. In general, it is more efficient to call CreateFontIndirect because CreateFont requires several parameters while CreateFontIndirect requires only one—a pointer to LOGFONT.

Before an application can actually begin drawing text with a logical font, it must find the closest match from the fonts stored internally on the device and the fonts whose resources have been loaded into the operating system. The fonts stored on the device or in the operating system are called physical fonts. The process of finding the physical font that most closely matches a specified logical font is called font mapping. This process occurs when an application calls the SelectObject function and supplies a handle identifying a logical font. Font mapping is performed by using an internal algorithm that compares the attributes of the requested logical font against the attributes of available physical fonts. When the font mapper algorithm completes its search and determines the closest possible match, the SelectObject function returns and the application can begin drawing text with the new font.

The SetMapperFlags function specifies whether or not the font mapper algorithm searches only for physical fonts with aspect ratios that match the physical device. The aspect ratio for a device is the ratio formed by the width and the height of a pixel on that device.

The system font (also known as the shell or default font) is the font used for text in the title bars, menus, and dialog boxes. On Windows 95/98 and Windows NT it is MS Sans Serif. On Windows 2000 it is Tahoma.


Special Font Selection Considerations

Although most font selection operations involve the user, there are some instances where this is not true. For example, a developer may want to use a unique font in an application to draw text in a control window. To select an appropriate font, the application must be able to determine what fonts are available, create a logical font that describes one of these available fonts, and then select that font into the appropriate device context.

An application can enumerate the available fonts by using the EnumFonts or EnumFontFamilies functions. EnumFontFamilies is recommended because it enumerates all the styles associated with a family name. This can be useful for fonts with many or unusual styles and for fonts that cross international borders.

Once an application has enumerated the available fonts and located an appropriate match, it should use the values returned by the font enumeration function to initialize the members of a LOGFONT structure. Then it can call the CreateFontIndirect function, passing to it a pointer to the initialized LOGFONT structure. If the CreateFontIndirect function is successful, the application can then select the logical font by calling the SelectObject function.When initializing the members of the LOGFONT structure, be sure to specify a specific character set in the lfCharSet member. This member is important in the font mapping process and the results will be inconsistent if this member is not initialized correctly. If you specify a typeface name in the lfFaceName member of the LOGFONT structure, make sure that the lfCharSet value matches the character set of the typeface specified in lfFaceName. For example, if you want to select a font such as MS Mincho, lfCharSet must be set to the predefined value SHIFTJIS_CHARSET.

The fonts for many East Asian languages have two typeface names: an English name and a localized name. For Windows 95/98 and Windows NT 4.0, CreateFont, CreateFontIndirect , and CreateFontIndirectEx take the localized typeface name for a system locale that matches the language, but they take the English typeface name for all other system locales. The best method is to try one name and, on failure, try the other. Note that EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font. On Windows 2000, this is no longer a problem because the font mapper for CreateFont, CreateFontIndirect, and CreateFontIndirectEx recognizes either typeface name, regardless of locale.


Embedded Fonts

Embedding a font is the technique of bundling a document and the fonts it contains into a file for transmission to another computer. Embedding a font guarantees that a font specified in a transmitted file will be present on the computer receiving the file. Not all fonts can be moved from computer to computer, however, since most fonts are licensed to only one computer at a time. Only TrueType and OpenType fonts can be embedded.

Applications should embed a font in a document only when requested by a user. An application cannot be distributed along with documents that contain embedded fonts, nor can an application itself contain an embedded font. Whenever an application distributes a font, in any format, the proprietary rights of the owner of the font must be acknowledged.

It may be a violation of a font vendor's proprietary rights or user license agreement to embed any fonts where embedding is not permitted or to fail to observe the following guidelines on embedding fonts. A font's license may give only read-write permission for a font to be installed and used on the destination computer. Or the license may give read-only permission. Read-only permission allows a document to be viewed and printed (but not modified) by the destination computer; documents with read-only embedded fonts are themselves read-only. Read-only embedded fonts may not be unbundled from the document and installed on the destination computer.

An application can determine the license status by calling the GetOutlineTextMetrics function and examining 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.

To embed a font, an application can use the GetFontData function to read the font file. Setting the dwTable and dwOffset parameters of GetFontData to 0L and the cbData parameter to –1L ensures that the application reads the entire font file from the beginning.

After an application retrieves the font data, it can store the data with the document by using any applicable format. Most applications build a font directory in the document, listing the embedded fonts and whether the embedding is read-write or read-only. An application can use the otmpStyleName and otmFamilyName members of the OUTLINETEXTMETRIC structure to identify the font.

If the read-only bit is set for the embedded font, applications must encrypt the font data before storing it with the document. The encryption method need not be complicated; for example, using the XOR operator to combine the font data with an application-defined constant is adequate and fast.


About Text Output

Text output is the most common type of graphic output found within the client area of Win32®-based applications. It is used by Win32-based applications in different ways. Word processing and desktop publishing applications create documents with formatted text; spreadsheet applications use text, numbers, and symbols to specify formulas, label columns, and list values; database applications create records and display queries with text, and CAD applications use text to label objects and display dimensions.

The Win32 API provides a complete set of functions to format and draw text in an application's client area and on a page of printer paper. These functions can be divided into two categories: those that format the text (or prepare it for output) and those that actually draw the text. The formatting functions align text, set the intercharacter spacing, set the text and text-background colors, and justify text. The drawing functions draw individual characters (or symbols) or entire strings of text.

When working with Microsoft® Windows® APIs, hard line breaks are specified with the carriage-return/line feed pair (\r\n).

The following topics discuss Win32 text:

  • Formatting Text
  • Drawing Text
  • Complex Scripts
  • ClearType Antialiasing


Formatting Text

The formatting functions can be divided into three categories: those that retrieve or set the text-formatting attributes for a device context, those that retrieve character widths, and those that retrieve string widths and heights.


Text-Formatting Attributes

An application can use six functions to set the text-formatting attributes for a device context: SetBkColor, SetBkMode, SetTextAlign, SetTextCharacterExtra, SetTextColor, and SetTextJustification. These functions affect the text alignment, the intercharacter spacing, the text justification, and text and background colors. In addition, six other functions can be used to retrieve the current text formatting attributes for any device context: GetBkColor, GetBkMode, GetTextAlign, GetTextCharacterExtra, GetTextColor, and GetTextExtentPoint32.

Text Alignment

Applications can use the SetTextAlign function to specify how the system should position the characters in a string of text when they call one of the drawing functions. This function can be used to position headings, page numbers, callouts, and so on. The system positions a string of text by aligning a reference point on an imaginary rectangle that surrounds the string, with the current cursor position or with a point passed as an argument to one of the text drawing functions. The SetTextAlign function lets the application specify the location of this reference point. The following is a list of the possible reference point locations.

Location | Description
left/bottom | The reference point is located at the bottom-left corner of the rectangle.
left/base line | The reference point is located at the intersection of the character-cell base line and the left edge of the rectangle.
left/top | The reference point is located at the top-left corner of the rectangle.
center/bottom | The reference point is located at the center of the bottom of the rectangle.
center/base line | The reference point is located at the intersection of the character-cell base line and the center of the rectangle.
center/top | The reference point is located at the center of the top of the rectangle.
right/bottom | The reference point is located at the bottom-right corner of the rectangle.
right/base line | The reference point is located at the intersection of the character-cell base line and the right edge of the rectangle.
right/top | The reference point is located at the top-right corner of the rectangle.

The following illustration shows a string of text drawn by calling the TextOut function. Before drawing the text, the SetTextAlign function was called to relocate the reference point at each one of the nine possible locations.

The default text alignment for a device context is the upper-left corner of the imaginary rectangle that surrounds the text. An application can retrieve the current text-alignment setting for any device context by calling the GetTextAlign function.

Intercharacter Spacing

Applications can use the SetTextCharacterExtra function to alter the intercharacter spacing for all text output operations in a specified device context. The following illustration shows a string of text drawn twice by calling the TextOut function. Before drawing the text the second time, the SetTextCharacterExtra function was called to increment the intercharacter spacing.

The default intercharacter spacing value for any device context is zero. An application can retrieve the current intercharacter spacing value for a device context by calling the GetTextCharacterExtra function.

Text Justification

Applications can use the GetTextExtentPoint32 and SetTextJustification functions to justify a line of text. Text justification is a common operation in any desktop publishing and in most word processing applications. The GetTextExtentPoint32 function computes the width and height of a string of text. After the width is computed, the application can call the SetTextJustification function to distribute extra spacing between each of the words in a line of text. The following illustration shows a paragraph of text printed twice: in the first paragraph, the text was not justified; in the second paragraph, the text was justified by calling the GetTextExtentPoint32 and SetTextJustification functions.

Text and Background Color

Applications can use the SetTextColor function to set the color of text drawn in the client-area of their windows, as well as the color of text drawn on a color printer. An application can use the SetBkColor function to set the color that appears behind each character and the SetBkMode function to specify how the system should blend the selected background color with the current color or colors on the video display.

The default text color for a display device context is black; the default background color is white; and the default background mode is OPAQUE. An application can retrieve the current text color for a device context by calling the GetTextColor function. An application can retrieve the current background color for a device context by calling the GetBkColor function and the current background mode by calling the GetBkMode function.


Character Widths

Applications need to retrieve character-width data when they perform such tasks as fitting strings of text to page or column widths. There are four functions that an application can use to retrieve character-width data. Two of these functions retrieve the character-advance width and two of these functions retrieve actual character-width data.

An application can use the GetCharWidth32 and GetCharWidthFloat functions to retrieve the advance width for individual characters or symbols in a string of text. The advance width is the distance that the cursor on a video display or the print-head on a printer must advance before printing the next character in a string of text. The GetCharWidth32 function returns the advance width as an integer value. If greater precision is required, an application can use the GetCharWidthFloat function to retrieve fractional advance-width values.

An application can retrieve actual character-width data by using the GetCharABCWidths and GetCharABCWidthsFloat functions. The GetCharABCWidthsFloat function works with all fonts. The GetCharABCWidths function only works with TrueType and OpenType fonts. For more information about TrueType and OpenType fonts, see Raster, Vector, TrueType, and OpenType Fonts.

The following illustration shows the three components of a character:

The A spacing is the width to add to the current position before placing the character. The B spacing is the width of the character itself. The C spacing is the white space to the right of the character. The total advance width is determined by calculating the sum of A+B+C. The character cell is an imaginary rectangle that surrounds each character or symbol in a font. Because characters can overhang or underhang the character cell, either or both of the A and C increments can be a negative number.


String Widths and Heights

In addition to retrieving character-width data for individual characters, applications also need to compute the width and height of entire strings. Two functions retrieve string-width and height measurements: GetTextExtentPoint32, and GetTabbedTextExtent. If the string does not contain tab characters, an application can use the GetTextExtentPoint32 function to retrieve the width and height of a specified string. If the string contains tab characters, an application should call the GetTabbedTextExtent function.

The Win32 API also supports a function, GetTextExtentExPoint, that applications can use for word-wrapping operations. This function returns the number of characters from a specified string that fit within a specified space.

Font Ascenders and Descenders

Some applications determine the line spacing between text lines of different sizes by using a font's maximum ascender and descender. An application can retrieve these values by calling the GetTextMetrics function and then checking the tmAscent and tmDescent members of the TEXTMETRIC.

The maximum ascent and descent are different from the typographic ascent and descent. In TrueType and OpenType fonts, the typographic ascent and descent are typically the top of the f glyph and bottom of the g glyph. An application can retrieve the typographic ascender and descender for a TrueType or OpenType font by calling the GetOutlineTextMetrics function and checking the values in the otmMacAscent and otmMacDescent members of the OUTLINETEXTMETRIC structure.

The following figure shows the difference between the vertical text metric values returned in the NEWTEXTMETRIC and OUTLINETEXTMETRIC structures. (The names beginning with otm are members of the OUTLINETEXTMETRIC structure.)

Font Dimensions

An application can retrieve the physical dimensions of a TrueType or OpenType font by calling the GetOutlineTextMetrics function. An application can retrieve the physical dimensions of any other font by calling the GetTextMetrics function. To determine the dimensions of an output device, an application can call the GetDeviceCaps function. GetDeviceCaps returns both physical and logical dimensions.

A logical inch is a measure the system uses to present legible fonts on the screen and is approximately 30 to 40 percent larger than a physical inch. The use of logical inches precludes an exact match between the output of the screen and printer. Developers should be aware that the text on a screen is not simply a scaled version of the text that will appear on the page, particularly if graphics are incorporated into the text.


Drawing Text

After an application selects the appropriate font, sets the required text-formatting options, and computes the necessary character width and height values for a string of text, it can begin drawing characters and symbols by calling any of the text-output functions:

  • DrawText
  • DrawTextEx
  • ExtTextOut
  • PolyTextOut
  • TabbedTextOut
  • TextOut

When an application calls one of these functions, the operating system passes the call to the graphics engine, which in turn passes the call to the appropriate device driver. At the device driver level, all of these calls are supported by one or more calls to the driver's own ExtTextOut or TextOut function. An application will achieve the fastest execution by calling ExtTextOut, which is quickly converted into an ExtTextOut call for the device. However, there are instances when an application should call one of the other three functions; for example, to draw multiple lines of text within the borders of a specified rectangular region, it is more efficient to call DrawText. To create a multicolumn table with justified columns of text, it is more efficient to call TabbedTextOut.


Complex Scripts

While the Win32 functions discussed in the preceding work well for many languages, they may not deal with the needs of complex scripts. Complex scripts are languages whose printed form is not rendered in a simple way. For example, a complex script may allow bidirectional rendering, contextual shaping of glyphs, or combining characters. Due to these special requirements, the control of text output must be very flexible.

Beginning with Windows 2000, the Win32 functions that display text—TextOut, ExtTextOut, TabbedTextOut, DrawText, and GetTextExtentExPoint—have been extended to support complex scripts. In general, this support is transparent to the application. However, applications should save characters in a buffer and display a whole line of text at one time, so that the complex script shaping modules can use context to reorder and generate glyphs correctly. In addition, because the width of a glyph can vary by context, applications should use GetTextExtentExPoint to determine line length rather than using cached character widths.

In addition, complex script-aware applications should consider adding support for right-to-left reading order and right alignment to their applications. You can toggle the reading order or alignment between left and right with the following code:

// Save lAlign (this example uses static variables)
static LONG lAlign = TA_LEFT;

// When user toggles alignment (assuming TA_CENTER is not supported).

lAlign = TA_RIGHT;

// When the user toggles reading order.

lAlign = TA_RTLREADING;

// Before calling ExtTextOut, for example, when processing WM_PAINT

SetTextAlign (hDc, lAlign);

To toggle both attributes at once, execute the following statement and then call SetTextAlign and ExtTextOut, as shown previously:

lAlign = TA_RIGHT^TA_RTLREADING;

You can also process complex scripts with Uniscribe. Uniscribe is a set of functions that allow a fine degree of control for complex scripts. For more information, see Uniscribe and Processing Complex Scripts.


ClearType Antialiasing

With Whistler, the Microsoft® ClearType™ antialiasing has been introduced. This smoothing method improves font display resolution over traditional anti-aliasing. It dramatically improves readability on color LCD monitors with a digital interface, such as those in laptops and high-quality flat desktop displays. Readability on CRT screens is also somewhat improved.

However, ClearType is dependent on the orientation and ordering of the LCD stripes. Currently, ClearType is implemented only for LCDs with vertical stripes that are ordered RGB. In particular, this affects tablet PCs, where the display can be oriented in any direction, and those screens that can be turned from landscape to portrait.

ClearType antialiasing is allowed:

  • For 16-, 24-, and 32-bit color (disabled for 256 colors or less)
  • For screen DC and memory DC (not for printer DC)
  • For TrueType fonts and OpenType fonts with TrueType outlines

ClearType antialiasing is disabled:

  • Under terminal server client
  • For bitmap fonts, vector fonts, device fonts, Type 1 fonts, or Postscript OpenType fonts without TrueType outlines
  • If the font has tuned embedded bitmaps, only for those font sizes that contain the embedded bitmaps

To activate ClearType antialiasing, call SystemParametersInfo once to turn on font smoothing and then a second time to set the smoothing type to FE_FONTSMOOTHINGCLEARTYPE, as shown in the following code sample:

SystemParametersInfo(SPI_SETFONTSMOOTHING,
                     TRUE,
                     0,
                     SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
SystemParametersInfo(SPI_SETFONTSMOOTHINGTYPE,
                     FE_FONTSMOOTHINGCLEARTYPE,
                     0,
                     SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

You can adjust the appearance of text by changing the contrast value used in the ClearType algorithm. The default is 1,400, but it can be any value from 1,000 to 2,200. Depending on the display device and the user's sensitivity to colors, a higher or lower contrast value may improve readability. To change the contrast, call SystemParametersInfo with SPI_SETFONTSMOOTHINGCONTRAST. The following code sets the contrast value to 1,600.

SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST,
                     1600,
                     0,
                     SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

You should consider the following details for application compatibility:

  • Text rendering with ClearType is slightly slower than with standard antialiasing.
  • Applications should not use XOR to display selected text. Applications should set the background color and redisplay the selected text.
  • Applications should not paint the same text on top of itselfin transparent mode. If this occurs, the edge pixels that are antialiased will color merge with themselves instead of with the background color. This results in darkened and colorful edges.
  • Applications should not paint text by painting the characters individually when in opaque mode because the edge of a character may be clipped by the following character. This occurs because a character that is smoothed with ClearType may have a negative A or C width where the regular character has a positive A or C width. Only the B width of the character is guaranteed to be the same. Likewise, applications should be careful if smoothed text is next to unsmoothed text.
  • If an application renders text and then manipulates the bitmap, font smoothing should be turned off by setting LOGFONT .lfQuality to NONANTIALIASED_QUALITY. For example, a game may add a bitmap shadow effect, or text rendered into a bitmap may be scaled to produce a thumbview.
  • If the user is running in portrait mode (that is, monitor striping is horizontal) ClearType antialiasing should be disabled.

With Whistler, the fdwQuality parameter in CreateFont and the lfQuality member of LOGFONT accept the CLEARTYPE_QUALITY flag. Rasterization of fonts created with this flag will use the ClearType rasterizer. This flag has no effect on previous versions of the operating system.


Using the Font and Text-Output Functions

This section describes how you can use the font and text-output functions to draw normal text, draw text from different fonts on the same line, rotate lines of text, display the font-selection common dialog-box, enumerate fonts, and so on:

  • Using a stock font to draw text
  • Creating a logical font
  • Enumerating the installed fonts
  • Checking the text capabilities of a device
  • Setting the text alignment
  • Drawing text from different fonts on the same line
  • Rotating lines of text
  • Retrieving character outlines
  • Using portable TrueType metrics
  • Using PANOSE numbers
  • Creating customized fonts


Using a Stock Font to Draw Text

The system provides six stock fonts. A stock font is a logical font that an application can obtain by calling the GetStockObject function and specifying the requested font. The following list contains the values that you can specify to obtain a stock font.

Value | Meaning
ANSI_FIXED_FONT | Specifies a monospace font based on the Windows character set. A Courier font is typically used.
ANSI_VAR_FONT | Specifies a proportional font based on the Microsoft® Windows® character set. MS Sans Serif is typically used.
DEVICE_DEFAULT_FONT | Specifies the preferred font for the specified device. This is typically the System font for display devices; however, for some dot-matrix printers this is a font that is resident on the device. (Printing with this font is usually faster than printing with a downloaded, bitmap font).
OEM_FIXED_FONT | Specifies a monospace font based on an OEM character set. For IBM computers and compatibles, the OEM font is based on the IBM PC character set.
SYSTEM_FONT | Specifies the System font. This is a proportional font based on the Windows character set, and is used by the operating system to display window titles, menu names, and text in dialog boxes. The System font is always available. Other fonts are available only if they have been installed.
SYSTEM_FIXED_FONT | Specifies a monospace font compatible with the System font in Windows versions earlier than 3.0.

The following example retrieves a handle to the variable stock font, selects it into a device context, and then writes a string using that font:

HFONT hfnt, hOldFont;

    hfnt = GetStockObject(ANSI_VAR_FONT);
    if (hOldFont = SelectObject(hdc, hfnt))
    {
        TextOut(hdc, 10, 50, "Sample ANSI_VAR_FONT text.", 26);
        SelectObject(hdc, hOldFont);
    }

If other stock fonts are not available, GetStockObject returns a handle to the System font (SYSTEM_FONT). You should use stock fonts only if the mapping mode for your application's device context is MM_TEXT.


Creating a Logical Font

You can use the Font common dialog box to display available fonts. The ChooseFont dialog box is displayed after an application initializes the members of a CHOOSEFONT structure and calls the ChooseFont function. After the user selects one of the available fonts and presses the OK button, the ChooseFont function initializes a LOGFONT structure with the relevant data. Your application can then call the CreateFontIndirect function and create a logical font based on the user's request. The following example demonstrates how this is done.

HFONT FAR PASCAL MyCreateFont( void )
{
    CHOOSEFONT cf;
    LOGFONT lf;
    HFONT hfont;

    // Initialize members of the CHOOSEFONT structure.

    cf.lStructSize = sizeof(CHOOSEFONT);
    cf.hwndOwner = (HWND)NULL;
    cf.hDC = (HDC)NULL;
    cf.lpLogFont = &lf;
    cf.iPointSize = 0;
    cf.Flags = CF_SCREENFONTS;
    cf.rgbColors = RGB(0,0,0);
    cf.lCustData = 0L;
    cf.lpfnHook = (LPCFHOOKPROC)NULL;
    cf.lpTemplateName = (LPSTR)NULL;
    cf.hInstance = (HINSTANCE) NULL;
    cf.lpszStyle = (LPSTR)NULL;
    cf.nFontType = SCREEN_FONTTYPE;
    cf.nSizeMin = 0;
    cf.nSizeMax = 0;

    // Display the CHOOSEFONT common-dialog box.

    ChooseFont(&cf);

    // Create a logical font based on the user's
    // selection and return a handle identifying
    // that font.

    hfont = CreateFontIndirect(cf.lpLogFont);
    return (hfont);
}


Enumerating the Installed Fonts

In some instances, an application must be able to enumerate the available fonts and select the one most appropriate for a particular operation. An application can enumerate the available fonts by calling the EnumFonts or EnumFontFamilies function. These functions send information about the available fonts to a callback function that the application supplies. The callback function receives information in LOGFONT and NEWTEXTMETRIC structures. (The NEWTEXTMETRIC structure contains information about a TrueType font. When the callback function receives information about a non-TrueType font, the information is contained in a TEXTMETRIC structure.) By using this information, an application can limit the user's choices to only those fonts that are available.

The EnumFontFamilies function is similar to the EnumFonts function but includes some extra functionality. EnumFontFamilies allows an application to take advantage of styles available with TrueType fonts. New and upgraded applications should use EnumFontFamilies instead of EnumFonts.

TrueType fonts are organized around a typeface name (for example, Courier New) and style names (for example, italic, bold, and extra-bold). The EnumFontFamilies function enumerates all the styles associated with a specified family name, not simply the bold and italic attributes. For example, when the system includes a TrueType font called Courier New Extra-Bold, EnumFontFamilies lists it with the other Courier New fonts. The capabilities of EnumFontFamilies are helpful for fonts with many or unusual styles and for fonts that cross international borders.

If an application does not supply a typeface name, the EnumFonts and EnumFontFamilies functions supply information about one font in each available family. To enumerate all the fonts in a device context, the application can specify NULL for the typeface name, compile a list of the available typefaces, and then enumerate each font in each typeface.

The following example uses the EnumFontFamilies function to retrieve the number of available raster, vector, and TrueType font families.

    UINT uAlignPrev;
    int aFontCount[] = { 0, 0, 0 };
    char szCount[8];

    EnumFontFamilies(hdc, (LPCTSTR) NULL,
        (FONTENUMPROC) EnumFamCallBack, (LPARAM) aFontCount);

    uAlignPrev = SetTextAlign(hdc, TA_UPDATECP);

    MoveToEx(hdc, 10, 50, (LPPOINT)NULL);
    TextOut(hdc, 0, 0, "Number of raster fonts: ", 24);
    itoa(aFontCount[0], szCount, 10);
    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    MoveToEx(hdc, 10, 75, (LPPOINT)NULL);
    TextOut(hdc, 0, 0, "Number of vector fonts: ", 24);
    itoa(aFontCount[1], szCount, 10);
    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    MoveToEx(hdc, 10, 100, (LPPOINT)NULL);
    TextOut(hdc, 0, 0, "Number of TrueType fonts: ", 26);
    itoa(aFontCount[2], szCount, 10);
    TextOut(hdc, 0, 0, szCount, strlen(szCount));

    SetTextAlign(hdc, uAlignPrev);

BOOL CALLBACK EnumFamCallBack(LPLOGFONT lplf, LPNEWTEXTMETRIC lpntm, DWORD FontType, LPVOID aFontCount)
{
    int far * aiFontCount = (int far *) aFontCount;

    // Record the number of raster, TrueType, and vector
    // fonts in the font-count array.

    if (FontType & RASTER_FONTTYPE)
        aiFontCount[0]++;
    else if (FontType & TRUETYPE_FONTTYPE)
        aiFontCount[2]++;
    else
        aiFontCount[1]++;

    if (aiFontCount[0] || aiFontCount[1] || aiFontCount[2])
        return TRUE;
    else
        return FALSE;

    UNREFERENCED_PARAMETER( lplf );
    UNREFERENCED_PARAMETER( lpntm );
}

This example uses two masks, RASTER_FONTTYPE and TRUETYPE_FONTTYPE, to determine the type of font being enumerated. If the RASTER_FONTTYPE bit is set, the font is a raster font. If the TRUETYPE_FONTTYPE bit is set, the font is a TrueType font. If neither bit is set, the font is a vector font. A third mask, DEVICE_FONTTYPE, is set when a device (for example, a laser printer) supports downloading TrueType fonts; it is zero if the device is a display adapter, dot-matrix printer, or other raster device. An application can also use the DEVICE_FONTTYPE mask to distinguish GDI-supplied raster fonts from device-supplied fonts. The system can simulate bold, italic, underline, and strikeout attributes for GDI-supplied raster fonts, but not for device-supplied fonts.

An application can also check bits 1 and 2 in the tmPitchAndFamily member of the NEWTEXTMETRIC structure to identify a TrueType font. If bit 1 is 0 and bit 2 is 1, the font is a TrueType font.

Vector fonts are categorized as OEM_CHARSET instead of ANSI_CHARSET. Some applications identify vector fonts by using this information, checking the tmCharSet member of the NEWTEXTMETRIC structure. This categorization usually prevents the font mapper from choosing vector fonts unless they are specifically requested. (Most applications no longer use vector fonts because their strokes are single lines and they take longer to draw than TrueType fonts, which offer many of the same scaling and rotation features that required vector fonts.)


Checking the Text Capabilities of a Device

You can use the EnumFonts and EnumFontFamilies functions to enumerate the fonts that are available in a printer-compatible memory device context. You can also use the GetDeviceCaps function to retrieve information about the text capabilities of a device. By calling the GetDeviceCaps function with the NUMFONTS index, you can determine the minimum number of fonts supported by a printer. (An individual printer may support more fonts than specified in the return value from GetDeviceCaps with the NUMFONTS index.) By using the TEXTCAPS index, you can identify many of the text capabilities of the specified device.


Setting the Text Alignment

You can query and set the text alignment for a device context by using the GetTextAlign and SetTextAlign functions. The text-alignment settings determine how text is positioned relative to a specified location. Text can be aligned to the right or left of the position or centered over it; it can also be aligned above or below the point.

The following example shows a method for determining which horizontal alignment flag is set:

switch ((TA_LEFT | TA_RIGHT | TA_CENTER) & GetTextAlign(hdc))
{
    case TA_LEFT:
       .
       .
       .
    case TA_RIGHT:
       .
       .
       .
    case TA_CENTER:
       .
       .
       .
}

You can also use the SetTextAlign function to update the current position when a text-output function is called. For instance, the following example uses the SetTextAlign function to update the current position when the TextOut function is called. In this example, the cArial parameter is an integer that specifies the number of Arial fonts.

UINT uAlignPrev;
char szCount[8];

uAlignPrev = SetTextAlign(hdc, TA_UPDATECP);
MoveToEx(hdc, 10, 50, (LPPOINT) NULL);
TextOut(hdc, 0, 0, "Number of Arial fonts: ", 23);
itoa(cArial, szCount, 10);

TextOut(hdc, 0, 0, (LPSTR) szCount, strlen(szCount));
SetTextAlign(hdc, uAlignPrev);

Note You should not use SetTextAlign with TA_UPDATECP when you are using ScriptStringOut, because selected text is not rendered correctly. If you must use this flag, you can unset and reset it as necessary to avoid the problem.


Drawing Text from Different Fonts on the Same Line

Different type styles within a font family can have different widths. For example, bold and italic styles of a family are always wider than the roman style for a specified point size. When you display or print several type styles on a single line, you must keep track of the width of the line to avoid having characters displayed or printed on top of one another.

You can use two functions to retrieve the width (or extent) of text in the current font. The GetTabbedTextExtent function computes the width and height of a character string. If the string contains one or more tab characters, the width of the string is based upon a specified array of tab-stop positions. The GetTextExtentPoint32 function computes the width and height of a line of text.

When necessary, the system synthesizes a font by changing the character bitmaps. To synthesize a character in a bold font, the system draws the character twice: once at the starting point, and again one pixel to the right of the starting point. To synthesize a character in an italic font, the system draws two rows of pixels at the bottom of the character cell, moves the starting point one pixel to the right, draws the next two rows, and continues until the character has been drawn. By shifting pixels, each character appears to be sheared to the right. The amount of shear is a function of the height of the character.

One way to write a line of text that contains multiple fonts is to use the GetTextExtentPoint32 function after each call to TextOut and add the length to a current position. The following example writes the line "This is a sample string." using bold characters for "This is a", switches to italic characters for "sample", then returns to bold characters for "string." After printing all the strings, it restores the system default characters.

int XIncrement;
int YStart;
TEXTMETRIC tm;
HFONT hfntDefault, hfntItalic, hfntBold;
SIZE sz;
LPSTR lpszString1 = "This is a ";
LPSTR lpszString2 = "sample ";
LPSTR lpszString3 = "string.";

// Create a bold and an italic logical font.

hfntItalic = MyCreateFont();
hfntBold = MyCreateFont();

// Select the bold font and draw the first string
// beginning at the specified point (XIncrement, YStart).

XIncrement = 10;
YStart = 50;
hfntDefault = SelectObject(hdc, hfntBold);
TextOut(hdc, XIncrement, YStart, lpszString1,
        lstrlen(lpszString1));

// Compute the length of the first string and add
// this value to the x-increment that is used for the
// text-output operation.

GetTextExtentPoint32(hdc, lpszString1,
                   lstrlen(lpszString1), &sz);
XIncrement += sz.cx;

// Retrieve the overhang value from the TEXTMETRIC
// structure and subtract it from the x-increment.
// (This is only necessary for non-TrueType raster
// fonts.)

GetTextMetrics(hdc, &tm);
XIncrement -= tm.tmOverhang;

// Select an italic font and draw the second string
// beginning at the point (XIncrement, YStart).

hfntBold = SelectObject(hdc, hfntItalic);
GetTextMetrics(hdc, &tm);
XIncrement -= tm.tmOverhang;
TextOut(hdc, XIncrement, YStart, lpszString2,
        lstrlen(lpszString2));

// Compute the length of the second string and add
// this value to the x-increment that is used for the
// text-output operation.

GetTextExtentPoint32(hdc, lpszString2, lstrlen(lpszString2), &sz);
XIncrement += sz.cx;

// Reselect the bold font and draw the third string
// beginning at the point (XIncrement, YStart).

SelectObject(hdc, hfntBold);
TextOut(hdc, XIncrement - tm.tmOverhang, YStart, lpszString3,
            lstrlen(lpszString3));

// Reselect the original font.

SelectObject(hdc, hfntDefault);

// Delete the bold and italic fonts.

DeleteObject(hfntItalic);
DeleteObject(hfntBold);

In this example, the GetTextExtentPoint32 function initializes the members of a SIZE structure with the length and height of the specified string. The GetTextMetrics function retrieves the overhang for the current font. Because the overhang is zero if the font is a TrueType font, the overhang value does not change the string placement. For raster fonts, however, it is important to use the overhang value.

The overhang is subtracted from the bold string once, to bring subsequent characters closer to the end of the string if the font is a raster font. Because overhang affects both the beginning and end of the italic string in a raster font, the glyphs start at the right of the specified location and end at the left of the endpoint of the last character cell. (The GetTextExtentPoint32 function retrieves the extent of the character cells, not the extent of the glyphs.) To account for the overhang in the raster italic string, the example subtracts the overhang before placing the string and subtracts it again before placing subsequent characters.

The SetTextJustification function adds extra space to the break characters in a line of text. You can use the GetTextExtentPoint function to determine the extent of a string, then subtract that extent from the total amount of space the line should occupy, and use the SetTextJustification function to distribute the extra space among the break characters in the string. The SetTextCharacterExtra function adds extra space to every character cell in the selected font, including the break character. (You can use the GetTextCharacterExtra function to determine the current amount of extra space being added to the character cells; the default setting is zero.)

You can place characters with greater precision by using the GetCharWidth32 or GetCharABCWidths function to retrieve the widths of individual characters in a font. The GetCharABCWidths function is more accurate than the GetCharWidth32 function, but it can only be used with TrueType fonts.

ABC spacing also allows an application to perform very accurate text alignment. For example, when the application right aligns a raster roman font without using ABC spacing, the advance width is calculated as the character width. This means the white space to the right of the glyph in the bitmap is aligned, not the glyph itself. By using ABC widths, applications have more flexibility in the placement and removal of white space when aligning text, because they have information that allows them to finely control intercharacter spacing.


Rotating Lines of Text

You can rotate TrueType fonts at any angle. This is useful for labeling charts and other illustrations. The following example rotates a string in 10-degree increments around the center of the client area by changing the value of the lfEscapement and lfOrientation members of the LOGFONT structure used to create the font.

RECT rc;
int angle;
HFONT hfnt, hfntPrev;
LPSTR lpszRotate = "String to be rotated.";

// Allocate memory for a LOGFONT structure.

PLOGFONT plf = (PLOGFONT) LocalAlloc(LPTR, sizeof(LOGFONT));

// Specify a font typeface name and weight.

lstrcpy(plf->lfFaceName, "Arial");
plf->lfWeight = FW_NORMAL;

// Retrieve the client-rectangle dimensions.

GetClientRect(hwnd, &rc);

// Set the background mode to transparent for the
// text-output operation.

SetBkMode(hdc, TRANSPARENT);

// Draw the string 36 times, rotating 10 degrees
// counter-clockwise each time.

for (angle = 0; angle < 3600; angle += 100)
{
    plf->lfEscapement = angle;
    hfnt = CreateFontIndirect(plf);
    hfntPrev = SelectObject(hdc, hfnt);
    TextOut(hdc, rc.right / 2, rc.bottom / 2,
        lpszRotate, lstrlen(lpszRotate));
    SelectObject(hdc, hfntPrev);
    DeleteObject(hfnt);
}

// Reset the background mode to its default.

SetBkMode(hdc, OPAQUE);

// Free the memory allocated for the LOGFONT structure.

LocalFree((LOCALHANDLE) plf);


Retrieving Character Outlines

You can use the GetGlyphOutline function to retrieve the outline of a glyph from a TrueType font. The glyph outline returned by the GetGlyphOutline function is for a grid-fitted glyph. (A grid-fitted glyph has been modified so that its bitmap image conforms as closely as possible to the original design of the glyph.) If your application requires an unmodified glyph outline, request the glyph outline for a character in a font whose size is equal to the font's em units. (To create a font with this size, set the lfHeight member of the LOGFONT structure to the negative of the value of the ntmSizeEM member of the NEWTEXTMETRIC structure.)

GetGlyphOutline returns the outline as a bitmap or as a series of polylines and splines. When an application retrieves a glyph outline as a series of polylines and splines, the information is returned in a TTPOLYGONHEADER structure followed by as many TTPOLYCURVE structures as required to describe the glyph. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point specified by the pfxStart member of the TTPOLYGONHEADER structure is the point where the outline for a contour begins. The TTPOLYCURVE structures that follow can be either polyline records or spline records.

To render a TrueType character outline, you must use both the polyline and the spline records. The system can render both polylines and splines easily. Each polyline and spline record contains as many sequential points as possible, to minimize the number of records returned.

The starting point specified in the TTPOLYGONHEADER structure is always on the outline of the glyph. The specified point serves as both the starting and ending points for the contour.


Polyline Records

Polyline records are a series of points; lines drawn between the points describe the outline of the character. A polyline record begins with the last point in the previous record (or, for the first record in the contour, the starting point). Each point in the record is on the glyph outline and can be connected simply by using straight lines.


Spline Records

Spline records represent the quadratic curves (that is, quadratic b-splines) used by TrueType. A spline record begins with the last point in the previous record (or for the first record in the contour, with the starting point). For the first spline record, the starting point and the last point in the record are on the glyph outline. For all other spline records, only the last point is on the glyph outline. All other points in the spline records are off the glyph outline and must be rendered as the control points of b-splines.

The last spline or polyline record in a contour always ends with the contour's starting point. This arrangement ensures that every contour is closed.

Because b-splines require three points (one point off the glyph outline between two points that are on the outline), you must perform some calculations when a spline record contains more than one off-curve point.

For example, if a spline record contains three points (A, B, and C) and it is not the first record, points A and B are off the glyph outline. To interpret point A, use the current position (which is always on the glyph outline) and the point on the glyph outline between points A and B. To find the midpoint (M) between A and B, you can perform the following calculation.

M = A + (B – A)/2

The midpoint between consecutive off-outline points in a spline record is a point on the glyph outline, according to the definition of the spline format used in TrueType fonts.

If the current position is designated by P, the two quadratic splines defined by this spline record are (P, A, M) and (M, B, C).


Using Portable TrueType Metrics

Applications that use the TrueType text metrics can achieve a high degree of printer and document portability; they can use TrueType metrics even if they must maintain compatibility with early 16-bit versions of Windows.

Design widths overcome most of the problems of device-dependent text introduced by physical devices. Design widths are a kind of logical width. Independent of any rasterization problems or scaling transformations, each glyph has a logical width and height. Composed to a logical page, each character in a string has a place that is independent of the physical device widths. Although a logical width implies that widths can be scaled linearly at all point sizes, this is not necessarily true for either nonportable or most TrueType fonts. At smaller point sizes, some glyphs are made wider relative to their height for better readability.

The characters in TrueType core fonts are designed against a 2048 by 2048 grid. The design width is the width of a character in these grid units. (TrueType supports any integer grid size up to 16,384 by 16,384; grid sizes that are integer powers of 2 scale faster than other grid sizes.)

The font outline is designed in notional units. The em square is the notional grid against which the font outline is fitted. (You can use the otmEMSquare member of OUTLINETEXTMETRIC and the ntmSizeEM member of NEWTEXTMETRIC to retrieve the size of the em square in notional units.) When a font is created that has a point size (in device units) equal to the size of its em square, the ABC widths for this font are the desired design widths. For example, assume the size of an em square is 1000 and the ABC widths of a character in the font are 150, 400, and 150. A character in this font that is 10 device units high would have ABC widths of 1.5, 4, and 1.5, respectively. Since the MM_TEXT mapping mode is most commonly used with fonts (and MM_TEXT is equivalent to device units), this is a simple calculation.

Because of the high resolution of TrueType design widths, applications that use them must take into account the large numeric values that can be created.


Device vs. Design Units

An application can retrieve font metrics for a physical font only after the font has been selected into a device context. When a font is selected into a device context, it is scaled for the device. The font metrics specific to the device are known as device units.

Portable metrics in fonts are known as design units. To apply to a specified device, design units must be converted to device units. Use the following formula to convert design units to device units.

DeviceUnits = (DesignUnits/unitsPerEm) * (PointSize/72) * DeviceResolution

The variables in this formula have the following meanings.

Variable | Description
DeviceUnits | Specifies the DesignUnits font metric converted to device units. This value is in the same units as the value specified for DeviceResolution.
DesignUnits | Specifies the font metric to be converted to device units. This value can be any font metric, including the width of a character or the ascender value for an entire font.
unitsPerEm | Specifies the em square size for the font.
PointSize | Specifies size of the font, in points. (One point equals 1/72 of an inch.)
DeviceResolution | Specifies number of device units (pixels) per inch. Typical values might be 300 for a laser printer or 96 for a VGA screen.

This formula should not be used to convert device units back to design units. Device units are always rounded to the nearest pixel. The propagated round-off error can become very large, especially when an application is working with screen sizes.

To request design units, create a logical font whose height is specified as –unitsPerEm. Applications can retrieve the value for unitsPerEm by calling the EnumFontFamilies function and checking the ntmSizeEM member of the NEWTEXTMETRIC structure.


Metrics for Portable Documents

The following table specifies the most important font metrics for applications that require portable documents and the functions that allow an application to retrieve them.

Function | Metric | Use
EnumFontFamilies | ntmSizeEM | Retrieval of design metrics; conversion to device metrics.
GetCharABCWidths | ABCWidths | Accurate placement of characters at the start and end of margins, picture boundaries, and other text breaks.
GetCharWidth32 | AdvanceWidths | Placement of characters on a line.
GetOutlineTextMetrics | otmfsType | Font-embedding bits.
 | otmsCharSlopeRise | Y-component for slope of cursor for italic fonts.
 | otmsCharSlopeRun | X-component for slope of cursor for italic fonts.
 | otmAscent | Line spacing.
 | otmDescent | Line spacing.
 | otmLineGap | Line spacing.
 | otmpFamilyName | Font identification.
 | otmpStyleName | Font identification.
 | otmpFullName | Font identification (typically, family and style name).

The otmsCharSlopeRise, otmsCharSlopeRun, otmAscent, otmDescent, and otmLineGap members of the OUTLINETEXTMETRIC structure are scaled or transformed to correspond to the current device mode and physical height (as specified in the tmHeight member of the NEWTEXTMETRIC structure).

Font identification is important in those instances when an application must select the same font—for example, when a document is reopened or moved to a different operating system. The font mapper always selects the correct font when an application requests a font by full name. The family and style names provide input to the standard font dialog box, which ensures that the selection bars are properly placed.

The otmsCharSlopeRise and otmsCharSlopeRun values are used to produce a close approximation of the main italic angle of the font. For typical roman fonts, otmsCharSlopeRise is 1 and otmsCharSlopeRun is 0. For italic fonts, the values attempt to approximate the sine and cosine of the main italic angle of the font (in counterclockwise degrees past vertical); note that the italic angle for upright fonts is 0. Because these values are not expressed in design units, they should not be converted into device units.

The character placement and line spacing metrics enable an application to compute device-independent line breaks that are portable across screens, printers, typesetters, and even platforms.

To perform device-independent page layout

  1. Normalize all design metrics to a common ultra-high resolution (UHR) value (for example, 65,536 DPI); this prevents round-off errors.
  2. Compute line breaks based on UHR metrics and physical page width; this yields a starting point and an ending point of a line within the text stream.
  3. Compute the device page width in device units (for example, pixels).
  4. Fit each line of text into the device page width, using the line breaks computed in step 2.
  5. Compute page breaks by using UHR metrics and the physical page length; this yields the number of lines per page.
  6. Compute the line heights in device units.
  7. Fit the lines of text onto the page, using the lines per page from step 5 and the line heights from step 6.

If all applications adopt these techniques, developers can virtually guarantee that documents moved from one application to another will retain their original appearance and format.


Using PANOSE Numbers

TrueType font files include PANOSE numbers, which applications can use to choose a font that closely matches their specifications. The PANOSE system classifies faces by 10 different attributes. For more information about these attributes, see PANOSE. A PANOSE structure is part of the OUTLINETEXTMETRIC structure (whose values are filled in by calling the GetOutlineTextMetrics function).

The PANOSE attributes are rated individually on a scale. The resulting values are concatenated to produce a number. Given this number for a font and a mathematical metric to measure distances in the PANOSE space, an application can determine the nearest neighbors.


Creating Customized Fonts

The system keeps a font table containing all the fonts that applications can use. The system chooses a font from this table when an application calls the CreateFont or CreateFontIndirect function. There can be up to 253 entries in the table.

A font resource is a group of individual fonts representing characters in a specified character set that have various combinations of heights, widths, and pitches. You can load font resources and add the fonts in each resource to the operating system font table by using the AddFontResource function. To remove a font resource from the font table, you can use the RemoveFontResource function.

After you add a font resource to the font table, you can use the individual fonts in the resource. In other words, the CreateFont function takes the fonts into account when it tries to match a physical font to the specified logical font. (Fonts in the table are never directly accessible to an application. They are available only through the CreateFontIndirect and CreateFont functions, which return the handles of the fonts, not their memory addresses.)

Whenever your application adds or removes a font resource, it should inform all other applications of the change by sending a WM_FONTCHANGE message to them. Use the following call to the SendMessage function to send the message to all windows.

SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);

You can use the GetProfileString function to search the [Fonts] section of the Win.ini file for the list of fonts that the user has used Control Panel to install.


Creating Font Resources

A font resource file is an empty .dll; it contains no code or data, but it does contain resources. You can create font resources by creating font files and adding them as resources to a font resource file.

To create a font resource file

  1. Create the font files.
  2. Create a resource-definition file for the font.
  3. Create a dummy code module.
  4. Create a module-definition file that describes the fonts and the devices that use the fonts.
  5. Compile and link the source files.

You can add a font file to an empty library, along with such resources as icons, cursors, and menus, by using resource compiler.

Note A complete explanation of how to create a font resource file is beyond the scope of this book. For more information on this topic, see the documentation provided with your application development tools.


Installing and Using an Embedded Font

You must separate an embedded font from the containing document and install it in the user's operating system before the system can use it. Although the exact procedure for separating the font from the document depends on the method used to embed it, your application should always perform these steps.

To install an embedded font

  1. Resolve name conflicts before installing the font.
  2. Write the font data to a file, decoding read-only fonts as necessary.
  3. Create a font resource file for the unembedded font using the CreateScalableFontResource function.

Only a TrueType font can be embedded.

Your application should avoid installing a font with the same name as a font that is already on the system. To determine whether there are duplicate style names, an application can compare the information returned by EnumFontFamilies against the family name and style name stored with the embedded font.

Read-Write Permission

Embedded fonts that have read-write permission (and that therefore can be permanently installed on the user's system) should be written to a file that has the .ttf file name extension.

Most applications put the files for embedded fonts that have read-write permission into either the System subdirectory of the user's Windows directory or into the application's working directory. Files for read-only embedded fonts are typically put into a temporary directory.

Before installing an embedded font, you must use the CreateScalableFontResource function to create a font resource file. Because the system cannot directly interpret the native TrueType font file format, it requires a file that mimics the standard .fon file (called a .fot file) to make internal bookkeeping and enumeration easier. The CreateScalableFontResource function produces a .fot file that contains the name of the TrueType font file. After this .fot file is produced, applications can use TrueType fonts transparently by using the AddFontResource, AddFontResourceEx, and RemoveFontResource functions. You can also use the CreateScalableFontResource function to install special fonts for logos, icons, and other graphics. Font resource files for read-only fonts should use a different extension (for example, .for) and should be hidden from other applications in the system by specifying 1 for the first parameter of CreateScalableFontResource.

Your application should offer users the option of permanently installing embedded fonts that have read-write permission. To permanently install a font, applications should concatenate the typeface and style names and then use the WriteProfileString function to insert this string along with the .fot file name in the [Fonts] section of the Win.ini file. A typical font entry in the [Fonts] section looks like the following example.

Times New Roman Bold (TrueType)=TIMESBD.FOT

Read-Only Permission

Embedded fonts with read-only permission should not use the .ttf extension and should avoid the .fot and .fon extensions. A typical file name extension for read-only embedded fonts is .ttr. Files for read-only embedded fonts must be removed from the operating system and from both physical and logical memory as soon as the containing document is closed, so their names do not need to be meaningful except to the application.

If a document contains one or more read-only embedded fonts, the user must not be permitted to edit the document. If the user is allowed to edit the document in any way, your application must first strip away and delete the read-only embedded fonts.

As mentioned earlier, read-only embedded fonts must be removed from the operating system and memory immediately when the document in which they are bundled is closed.

To delete read-only embedded fonts

  1. Call the RemoveFontResource function for each font to be deleted.
  2. Delete the font resource file for each font.
  3. Delete each TrueType font file for each font.

When an application creates a file for a read-only embedded font and specifies 1 for the first parameter of the CreateScalableFontResource function, the EnumFonts and EnumFontFamilies functions will not enumerate this font. Hiding read-only embedded fonts in this manner makes it unlikely that another application can use them, even though resources are theoretically available to all processes. The RemoveFontResource function does not delete a font currently in use. If your application uses a read-only embedded font installed by another application, it can be difficult for the installing application to delete the font. In this case, your application should delete the resource file and the TrueType font file when the user closes the document containing the read-only fonts.

It is very important that applications delete the TrueType font file for read-only embedded fonts. If the delete operation fails when the user closes the document, the application should periodically attempt to delete the file as the application runs, when it closes, and the next time it starts.

In some cases, an application is unable to delete a TrueType font file for a read-only embedded font because of external events (such as a system failure). There is no legal liability for events that are out of the control of the application.


Font and Text Reference

The following elements are used with fonts and text:

  • Font and Text Functions
  • Font and Text Structures
  • Font and Text Messages


Font and Text Functions

The following functions are used with fonts and text.

Function | Description
AddFontMemResourceEx | Adds an embedded font to the system font table.
AddFontResource | Adds a font resource to the system font table.
AddFontResourceEx | Adds a private or non-enumerable font to the system font table.
CreateFont | Creates a logical font.
CreateFontIndirect | Creates a logical font from a structure.
CreateFontIndirectEx | Creates a logical font from a structure.
CreateScalableFontResource | Creates a font resource file for a scalable font.
DrawText | Draws formatted text in a rectangle.
DrawTextEx | Draws formatted text in rectangle.
EnumFontFamExProc | An application defined–callback function used with EnumFontFamiliesEx to process fonts.
EnumFontFamiliesEx | Enumerates all fonts in the system with certain characteristics.
ExtTextOut | Draws a character string.
GetAspectRatioFilterEx | Gets the setting for the aspect-ratio filter.
GetCharABCWidths | Gets the widths of consecutive characters from the TrueType font.
GetCharABCWidthsFloat | Gets the widths of consecutive characters from the current font.
GetCharABCWidthsI | Gets the widths of consecutive glyph indices or from an array of glyph indices from the TrueType font.
GetCharacterPlacement | Gets information about a character string.
GetCharWidth32 | Gets the widths of consecutive characters from the current font.
GetCharWidthFloat | Gets the fractional widths of consecutive characters from the current font.
GetCharWidthI | Gets the widths of consecutive glyph indices or an array of glyph indices from the current font.
GetFontData | Gets metric data for a TrueType font.
GetFontLanguageInfo | Returns information about the selected font for a display context.
GetFontUnicodeRanges | Tells which Unicode characters are supported by a font.
GetGlyphIndices | Translates a string into an array of glyph indices.
GetGlyphOutline | Gets the outline or bitmap for a character in the TrueType font.
GetKerningPairs | Gets the character-kerning pairs for a font.
GetOutlineTextMetrics | Gets text metrics for TrueType fonts.
GetRasterizerCaps | Tells whether TrueType fonts are installed.
GetTabbedTextExtent | Computes the width and height of a character string, including tabs.
GetTextAlign | Gets the text-alignment setting for a device context.
GetTextCharacterExtra | Gets the current intercharacter spacing for a device context.
GetTextColor | Gets the text color for a device context.
GetTextExtentExPoint | Gets the number of characters in a string that will fit within a space.
GetTextExtentExPointI | Gets the number of glyph indices that will fit within a space.
GetTextExtentPoint32 | Computes the width and height of a string of text.
GetTextExtentPointI | Computes the width and height of an array of glyph indices.
GetTextFace | Gets the name of the font that is selected into a device context.
GetTextMetrics | Fills a buffer with the metrics for a font.
PolyTextOut | Draws several strings using the font and text colors in a device context.
RemoveFontMemResourceEx | Removes a font whose source was embedded in a document from the system font table.
RemoveFontResource | Removes the fonts in a file from the system font table.
RemoveFontResourceEx | Removes a private or non-enumerable font from the system font table.
SetMapperFlags | Alters the algorithm used to map logical fonts to physical fonts.
SetTextAlign | Sets the text-alignment flags for a device context.
SetTextCharacterExtra | Sets the intercharacter spacing.
SetTextColor | Sets the text color for a device context.
SetTextJustification | Specifies the amount of space the system should add to the break characters in a string.
TabbedTextOut | Writes a character string at a location, expanding tabs to specified values.
TextOut | Writes a character string at a location.

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of the Microsoft® Windows® operating system.

EnumFontFamilies
EnumFontFamProc
EnumFonts
EnumFontsProc
GetCharWidth
GetTextExtentPoint


AddFontMemResourceEx

The AddFontMemResourceEx function adds the font resource from a memory image to the system.

HANDLE AddFontMemResourceEx(
  PVOID pbFont,       // font resource
  DWORD cbFont,       // number of bytes in font resource
  PVOID pdv,          // Reserved. Must be 0.
  DWORD *pcFonts      // number of fonts installed
);

Parameters

pbFont
[in] Pointer to a font resource.
cbFont
[in] Number of bytes in the font resource that is pointed to by pbFont.
pdv
[in] Reserved. Must be 0.
pcFonts
[in] Pointer to a variable that specifies the number of fonts installed.

Return Values

If the function succeeds, the return value specifies the handle to the font added. This handle uniquely identifies the fonts that were installed on the system. If the function fails, the return value is zero.

Remarks

This function allows an application to get a font that is embedded in a document or a Web page. A font that is added by AddFontMemResourceEx is always private to the process that made the call and is not enumerable.

A memory image can contain more than one font. When this function succeeds, pcFonts is a pointer to a DWORD whose value is the number of fonts added to the system as a result of this call. For example, this number could be 2 for the vertical and horizontal faces of an Asian font.

When the function succeeds, the caller of this function can free the memory pointed to by pbFont because the system has made its own copy of the memory. To remove the fonts that were installed, call RemoveFontMemResourceEx. However, when the process goes away, the system will unload the fonts even if the process did not call RemoveFontMemResource.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, RemoveFontMemResourceEx, SendMessage, DESIGNVECTOR


AddFontResource

The AddFontResource function adds the font resource from the specified file to the system font table. The font can subsequently be used for text output by any Win32-based application.

To mark a font as private or no enumerable, use the AddFontResourceEx function.

int AddFontResource(
  LPCTSTR lpszFilename   // font file name
);

Parameters

lpszFilename
[in] Pointer to a null-terminated character string that contains a valid font file name. This parameter can specify any of the following files.
File extension | Description
.fon | Font resource file.
.fnt | Raw bitmap font file.
.ttf | Raw TrueType file.
.ttc | Windows 95/98 East Asian and Windows NT: TrueType font collection.
.fot | TrueType resource file.
.otf | PostScript OpenType font.
.mmm | multiple master Type1 font resource file. It must be used with .pfm and .pfb files.
.pfb | Type 1 font bits file. It is used with a .pfm file.
.pfm | Type 1 font metrics file. It is used with a .pfb file.

Windows 2000 or later: To add a font whose information comes from several resource files, have lpszFileName point to a string with the file names separated by a | --for example, abcxxxxx.pfm | abcxxxxx.pfb.

Return Values

If the function succeeds, the return value specifies the number of fonts added.

If the function fails, the return value is zero.

Remarks

Any application that adds or removes fonts from the system font table should notify other windows of the change by sending a WM_FONTCHANGE message to all top-level windows in the operating system. The application should send this message by calling the SendMessage function and setting the hwnd parameter to HWND_BROADCAST.

When an application no longer needs a font resource that it loaded by calling the AddFontResource function, it must remove that resource by calling the RemoveFontResource function.

This function installs the font only for the current session. When the system restarts, the font will not be present. To have the font installed even after restarting the system, the font must be listed in the registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, AddFontResourceEx, RemoveFontResource, SendMessage


AddFontResourceEx

The AddFontResourceEx function adds the font resource from the specified file to the system. Fonts added with the AddFontResourceEx function can be marked as private and not enumerable.

int AddFontResourceEx(
  LPCTSTR lpszFilename, // font file name
  DWORD fl,             // font characteristics
  PVOID pdv             // reserved
);

Parameters

lpszFilename
[in] Pointer to a null-terminated character string that contains a valid font file file name. This parameter can specify any of the following files.
File extension | Description
.fon | Font resource file.
.fnt | Raw bitmap font file.
.ttf | Raw TrueType file.
.ttc | Windows 95/98 East Asian and Windows NT: True Type font collection.
.fot | TrueType resource file.
.otf | PostScript OpenType font.
.mmm | multiple master Type1 font resource file. It must be used with .pfm and .pfb files.
.pfb | Type 1 font bits file. It is used with a .pfm file.
.pfm | Type 1 font metrics file. It is used with a .pfb file.

To add a font whose information comes from several resource files, point lpszFileName to a string with the file names separated by a | --for example, abcxxxxx.pfm | abcxxxxx.pfb.

fl
[in] Specifies characteristics of the font to be added to the system. This parameter can be one of the following values.
Value | Meaning
FR_PRIVATE | Specifies that only the process that called the AddFontResourceEx function can use this font. When the font name matches a public font, the private font will be chosen. When the process terminates, the system will remove all fonts installed by the process with the AddFontResourceEx function.
FR_NOT_ENUM | Specifies that no process, including the process that called the AddFontResourceEx function, can enumerate this font.

pdv
[in] Reserved. It must be 0.

Return Values

If the function succeeds, the return value specifies the number of fonts added.

If the function fails, the return value is zero.

Remarks

This function allows a process to use fonts without allowing other processes access to the fonts.

When an application no longer needs a font resource it loaded by calling the AddFontResourceEx function, it must remove the resource by calling the RemoveFontResourceEx function.

This function installs the font only for the current session. When the system restarts, the font will not be present. To have the font installed even after restarting the system, the font must be listed in the registry.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Fonts and Text Overview, Font and Text Functions, RemoveFontResourceEx, SendMessage


CreateFont

The CreateFont function creates a logical font with the specified characteristics. The logical font can subsequently be selected as the font for any device.

HFONT CreateFont(
  int nHeight,               // height of font
  int nWidth,                // average character width
  int nEscapement,           // angle of escapement
  int nOrientation,          // base-line orientation angle
  int fnWeight,              // font weight
  DWORD fdwItalic,           // italic attribute option
  DWORD fdwUnderline,        // underline attribute option
  DWORD fdwStrikeOut,        // strikeout attribute option
  DWORD fdwCharSet,          // character set identifier
  DWORD fdwOutputPrecision,  // output precision
  DWORD fdwClipPrecision,    // clipping precision
  DWORD fdwQuality,          // output quality
  DWORD fdwPitchAndFamily,   // pitch and family
  LPCTSTR lpszFace           // typeface name
);

Parameters

nHeight
[in] Specifies the height, in logical units, of the font's character cell or character. The character height value (also known as the em height) is the character cell height value minus the internal-leading value. The font mapper interprets the value specified in nHeight in the following manner.
Value | Meaning
> 0 | The font mapper transforms this value into device units and matches it against the cell height of the available fonts.
0 | The font mapper uses a default height value when it searches for a match.
< 0 | The font mapper transforms this value into device units and matches its absolute value against the character height of the available fonts.

For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size.

This mapping occurs when the font is used for the first time.

For the MM_TEXT mapping mode, you can use the following formula to specify a height for a font with a specified point size:

nHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
nWidth
[in] Specifies the average width, in logical units, of characters in the requested font. If this value is zero, the font mapper chooses a closest match value. The closest match value is determined by comparing the absolute values of the difference between the current device's aspect ratio and the digitized aspect ratio of available fonts.
nEscapement
[in] Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text.

Windows NT/2000 or later: When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters.

When the graphics mode is set to GM_COMPATIBLE, nEscapement specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

Windows 95: The nEscapement parameter specifies both the escapement and orientation. You should set nEscapement and nOrientation to the same value.

nOrientation
[in] Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device.
fnWeight
[in] Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.

The following values are defined for convenience.
Value | Weight
FW_DONTCARE | 0
FW_THIN | 100
FW_EXTRALIGHT | 200
FW_ULTRALIGHT | 200
FW_LIGHT | 300
FW_NORMAL | 400
FW_REGULAR | 400
FW_MEDIUM | 500
FW_SEMIBOLD | 600
FW_DEMIBOLD | 600
FW_BOLD | 700
FW_EXTRABOLD | 800
FW_ULTRABOLD | 800
FW_HEAVY | 900
FW_BLACK | 900

fdwItalic
[in] Specifies an italic font if set to TRUE.
fdwUnderline
[in] Specifies an underlined font if set to TRUE.
fdwStrikeOut
[in] Specifies a strikeout font if set to TRUE.
fdwCharSet
[in] Specifies the character set. The following values are predefined:

ANSI_CHARSET
BALTIC_CHARSET
CHINESEBIG5_CHARSET
DEFAULT_CHARSET
EASTEUROPE_CHARSET
GB2312_CHARSET
GREEK_CHARSET
HANGUL_CHARSET
MAC_CHARSET
OEM_CHARSET
RUSSIAN_CHARSET
SHIFTJIS_CHARSET
SYMBOL_CHARSET
TURKISH_CHARSET

Windows NT/2000 or Middle-Eastern Windows 3.1 or later:
HEBREW_CHARSET
ARABIC_CHARSET
Windows NT/2000 or Thai Windows 3.1 or later:
THAI_CHARSET

The OEM_CHARSET value specifies a character set that is operating-system dependent.

Windows 95/98/Me: You can use the DEFAULT_CHARSET value to allow the name and size of a font to fully describe the logical font. If the specified font name does not exist, a font from any character set can be substituted for the specified font, so you should use DEFAULT_CHARSET sparingly to avoid unexpected results.

Windows NT/2000 or later: DEFAULT_CHARSET is set to a value based on the current system locale. For example, when the system locale is English (United States), it is set as ANSI_CHARSET.

Fonts with other character sets may exist in the operating system. If an application uses a font with an unknown character set, it should not attempt to translate or interpret strings that are rendered with that font.

To ensure consistent results when creating a font, do not specify OEM_CHARSET or DEFAULT_CHARSET. If you specify a typeface name in the lpszFace parameter, make sure that the fdwCharSet value matches the character set of the typeface specified in lpszFace.

fdwOutputPrecision
[in] Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It can be one of the following values.
Value | Meaning
OUT_CHARACTER_PRECIS | Not used.
OUT_DEFAULT_PRECIS | Specifies the default font mapper behavior.
OUT_DEVICE_PRECIS | Instructs the font mapper to choose a Device font when the system contains multiple fonts with the same name.
OUT_OUTLINE_PRECIS | Windows NT/2000 or later: This value instructs the font mapper to choose from TrueType and other outline-based fonts.
OUT_RASTER_PRECIS | Instructs the font mapper to choose a raster font when the system contains multiple fonts with the same name.
OUT_STRING_PRECIS | This value is not used by the font mapper, but it is returned when raster fonts are enumerated.
OUT_STROKE_PRECIS Windows NT/2000 or later: This value is not used by the font mapper, but it is returned when TrueType, other outline-based fonts, and vector fonts are enumerated.

Windows 95/98/Me: This value is used to map vector fonts, and is returned when TrueType or vector fonts are enumerated.

OUT_TT_ONLY_PRECIS | Instructs the font mapper to choose from only TrueType fonts. If there are no TrueType fonts installed in the system, the font mapper returns to default behavior.
OUT_TT_PRECIS | Instructs the font mapper to choose a TrueType font when the system contains multiple fonts with the same name.

Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the operating system contains more than one font with a specified name. For example, if an operating system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. Specifying OUT_TT_ONLY_PRECIS forces the font mapper to choose a TrueType font, even if it must substitute a TrueType font of another name.

fdwClipPrecision
[in] Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be one or more of the following values.
Value | Meaning
CLIP_DEFAULT_PRECIS | Specifies default clipping behavior.
CLIP_CHARACTER_PRECIS | Not used.
CLIP_STROKE_PRECIS Not used by the font mapper, but is returned when raster, vector, or TrueType fonts are enumerated.

Windows NT/2000 or later: For compatibility, this value is always returned when enumerating fonts.
CLIP_MASK | Not used.
CLIP_EMBEDDED | You must specify this flag to use an embedded read-only font.
CLIP_LH_ANGLES When this value is used, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed.

If not used, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system.

For more information about the orientation of coordinate systems, see the description of the nOrientation parameter
CLIP_TT_ALWAYS | Not used.

fdwQuality
[in] Specifies the output quality. The output quality defines how carefully GDI must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values.
Value | Meaning
ANTIALIASED_QUALITY Windows NT 4.0 and later: Font is antialiased, or smoothed, if the font supports it and the size of the font is not too small or too large.

Windows 95 with Plus! and later: In addition to the comments for Windows NT, the display must greater than 8-bit color, it must be a single plane device, it cannot be a palette display, and it cannot be in a multiple display monitor setup. In addition, you must select a TrueType font into a screen DC prior to using it in a DIBSection, otherwise antialiasing does not happen.
CLEARTYPE_QUALITY | Whistler: If set, text is rendered (when possible) using ClearType antialiasing method. See Remarks for more information.
DEFAULT_QUALITY | Appearance of the font does not matter.
DRAFT_QUALITY | Appearance of the font is less important than when the PROOF_QUALITY value is used. For GDI raster fonts, scaling is enabled, which means that more font sizes are available, but the quality may be lower. Bold, italic, underline, and strikeout fonts are synthesized, if necessary.
NONANTIALIASED_QUALITY | Windows 95 with Plus!, Windows 98, Windows NT 4.0, and Windows 2000 or later: Font is never antialiased, that is, font smoothing is not done.
PROOF_QUALITY | Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Although the chosen font size may not be mapped exactly when PROOF_QUALITY is used, the quality of the font is high and there is no distortion of appearance. Bold, italic, underline, and strikeout fonts are synthesized, if necessary.

If neither ANTIALIASED_QUALITY nor NONANTIALIASED_QUALITY is selected, the font is antialiased only if the user chooses "smooth screen fonts" in Control Panel.

fdwPitchAndFamily
[in] Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be one of the following values:
  • DEFAULT_PITCH
  • FIXED_PITCH
  • VARIABLE_PITCH

The four high-order bits specify the font family and can be one of the following values.
Value | Description
FF_DECORATIVE | Novelty fonts. Old English is an example.
FF_DONTCARE | Don't care or don't know.
FF_MODERN | Fonts with constant stroke width, with or without serifs. Pica, Elite, and Courier New® are examples.
FF_ROMAN | Fonts with variable stroke width and with serifs. MS® Serif is an example.
FF_SCRIPT | Fonts designed to look like handwriting. Script and Cursive are examples.
FF_SWISS | Fonts with variable stroke width and without serifs. MS Sans Serif is an example.

An application can specify a value for the fdwPitchAndFamily parameter by using the Boolean OR operator to join a pitch constant with a family constant.

Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface requested is not available.

lpszFace
[in] Pointer to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts. For more information, see the Remarks.

If lpszFace is NULL or empty string, GDI uses the first font that matches the other specified attributes.

Return Values

If the function succeeds, the return value is a handle to a logical font.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When you no longer need the font, call the DeleteObject function to delete it.

To help protect the copyrights of vendors who provide fonts for Windows 95/98 and Windows NT/Windows 2000, Win32-based applications should always report the exact name of a selected font. Because available fonts can vary from system to system, do not assume that the selected font is always the same as the requested font. For example, if you request a font named Palatino, but no such font is available on the system, the font mapper will substitute a font that has similar attributes but a different name. Always report the name of the selected font to the user.

Windows 95/98 and Windows NT 4.0: The fonts for many East Asian languages have two typeface names: an English name and a localized name. CreateFont, CreateFontIndirect and CreateFontIndirectEx take the localized typeface name on a system locale that matches the language, but they take the English typeface name on all other system locales. The best method is to try one name and, on failure, try the other. Note that EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

Windows 2000 or later: The font mapper for CreateFont, CreateFontIndirect, and CreateFontIndirectEx recognizes both the English and the localized typeface name, regardless of locale.

Whistler: The following situations do not support ClearType antialiasing:

  • Text rendered on a printer.
  • A display set for 256 colors or less.
  • Text rendered to a terminal server client.
  • The font is not a TrueType font or an OpenType font with TrueType outlines. For example, the following do not support ClearType antialiasing: Type 1 fonts, Postscript OpenType fonts without TrueType outlines, bitmap fonts, vector fonts, and device fonts .
  • The font has tuned embedded bitmaps, only for the font sizes that contain the embedded bitmaps. For example, this occurs commonly in East Asian fonts.

For an example, see Setting Fonts for Menu-Item Text Strings.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, CreateFontIndirect, CreateFontIndirectEx, DeleteObject, EnumFonts, EnumFontFamilies, EnumFontFamiliesEx, SelectObject, EnumFontFamilies


CreateFontIndirect

The CreateFontIndirect function creates a logical font that has the specified characteristics. The font can subsequently be selected as the current font for any device context.

HFONT CreateFontIndirect(
  CONST LOGFONT* lplf   // characteristics
);

Parameters

lplf
[in] Pointer to a LOGFONT structure that defines the characteristics of the logical font.

Return Values

If the function succeeds, the return value is a handle to a logical font.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The CreateFontIndirect function creates a logical font with the characteristics specified in the LOGFONT structure. When this font is selected by using the SelectObject function, GDI's font mapper attempts to match the logical font with an existing physical font. If it fails to find an exact match, it provides an alternative whose characteristics match as many of the requested characteristics as possible.

When you no longer need the font, call the DeleteObject function to delete it.

Windows 95/98 and Windows NT 4.0: The fonts for many East Asian languages have two typeface names: an English name and a localized name. CreateFont, CreateFontIndirect, and CreateFontIndirectEx take the localized typeface name only on a system locale that matches the language, while they take the English typeface name on all other system locales. The best method is to try one name and, on failure, try the other. Note that EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

Windows 2000 or later: The font mapper for CreateFont, CreateFontIndirect, and CreateFontIndirectEx recognizes both the English and the localized typeface name, regardless of locale.

For an example, see Creating a Logical Font.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, CreateFont, CreateFontIndirectEx, DeleteObject, EnumFonts, EnumFontFamilies, EnumFontFamiliesEx, LOGFONT, SelectObject


CreateFontIndirectEx

The CreateFontIndirectEx function specifies a logical font that has the characteristics in the specified structure. The font can subsequently be selected as the current font for any device context.

HFONT CreateFontIndirectEx(
  CONST ENUMLOGFONTEXDV *penumlfex   // characteristiccs
);

Parameters

penumlfex
[in] Pointer to an ENUMLOGFONTEXDV structure that defines the characteristics of a multiple master font.

Note, this function ignores the elfDesignVector member in ENUMLOGFONTEXDV.

Return Values

If the function succeeds, the return value is the handle to the new ENUMLOGFONTEXDV structure.

If the function fails, the return value is zero.

Remarks

The CreateFontIndirectEx function creates a logical font with the characteristics specified in the ENUMLOGFONTEXDV structure. When this font is selected by using the SelectObject function, GDI's font mapper attempts to match the logical font with an existing physical font. If it fails to find an exact match, it provides an alternative whose characteristics match as many of the requested characteristics as possible.

When you no longer need the font, call the DeleteObject function to delete it.

Windows 95/98 and Windows NT 4.0: The fonts for many East Asian languages have two typeface names: an English name and a localized name. CreateFont, CreateFontIndirect, and CreateFontIndirectEx take the localized typeface name only on a system locale that matches the language, while they take the English typeface name on all other system locales. The best method is to try one name and, on failure, try the other. Note that EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

Windows 2000 or later: The font mapper for CreateFont, CreateFontIndirect, and CreateFontIndirectEx recognizes both the English and the localized typeface name, regardless of locale.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, CreateFont, CreateFontIndirect, EnumFonts, EnumFontFamilies, EnumFontFamiliesEx, ENUMLOGFONTEXDV


CreateScalableFontResource

The CreateScalableFontResource function creates a font resource file for a scalable font.

BOOL CreateScalableFontResource(
  DWORD fdwHidden,          // read-only option
  LPCTSTR lpszFontRes,      // font file name
  LPCTSTR lpszFontFile,     // scalable font file name
  LPCTSTR lpszCurrentPath   // scalable font file path
);

Parameters

fdwHidden
[in] Specifies whether the font is a read-only font. This parameter can be one of the following values.
Value | Meaning
0 | The font has read-write permission.
1 | The font has read-only permission and should be hidden from other applications in the system. When this flag is set, the font is not enumerated by the EnumFonts or EnumFontFamilies function.

lpszFontRes
[in] Pointer to a null-terminated string specifying the name of the font resource file to create. If this parameter specifies an existing font resource file, the function fails.
lpszFontFile
[in] Pointer to a null-terminated string specifying the name of the scalable font file that this function uses to create the font resource file.
lpszCurrentPath
[in] Pointer to a null-terminated string specifying the path to the scalable font file.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError. If lpszFontRes specifies an existing font file, GetLastError returns ERROR_FILE_EXISTS

Remarks

The CreateScalableFontResource function is used by applications that install TrueType fonts. An application uses the CreateScalableFontResource function to create a font resource file (typically with a .fot file name extension) and then uses the AddFontResource function to install the font. The TrueType font file (typically with a .ttf file name extension) must be in the System subdirectory of the Windows directory to be used by the AddFontResource function.

The CreateScalableFontResource function currently supports only TrueType-technology scalable fonts.

When the lpszFontFile parameter specifies only a file name and extension, the lpszCurrentPath parameter must specify a path. When the lpszFontFile parameter specifies a full path, the lpszCurrentPath parameter must be NULL or a pointer to NULL.

When only a file name and extension are specified in the lpszFontFile parameter and a path is specified in the lpszCurrentPath parameter, the string in lpszFontFile is copied into the .fot file as the .ttf file that belongs to this resource. When the AddFontResource function is called, the operating system assumes that the .ttf file has been copied into the System directory (or into the main Windows directory in the case of a network installation). The .ttf file need not be in this directory when the CreateScalableFontResource function is called, because the lpszCurrentPath parameter contains the directory information. A resource created in this manner does not contain absolute path information and can be used in any installation.

When a path is specified in the lpszFontFile parameter and NULL is specified in the lpszCurrentPath parameter, the string in lpszFontFile is copied into the .fot file. In this case, when the AddFontResource function is called, the .ttf file must be at the location specified in the lpszFontFile parameter when the CreateScalableFontResource function was called; the lpszCurrentPath parameter is not needed. A resource created in this manner contains absolute references to paths and drives and does not work if the .ttf file is moved to a different location.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, AddFontResource, EnumFonts, EnumFontFamilies


DrawText

The DrawText function draws formatted text in the specified rectangle. It formats the text according to the specified method (expanding tabs, justifying characters, breaking lines, and so forth).

To specify additional formatting options, use the DrawTextEx function.

int DrawText(
  HDC hDC,          // handle to DC
  LPCTSTR lpString, // text to draw
  int nCount,       // text length
  LPRECT lpRect,    // formatting dimensions
  UINT uFormat      // text-drawing options
);

Parameters

hDC
[in] Handle to the device context.
lpString
[in] Pointer to the string that specifies the text to be drawn. If the nCount parameter is –1, the string must be null-terminated.

If uFormat includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.

nCount
[in] Specifies the length of the string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs. If nCount is –1, then the lpString parameter is assumed to be a pointer to a null-terminated string and DrawText computes the character count automatically.

Windows 95/98/Me: This number many not exceed 8192.

lpRect
[in/out] Pointer to a RECT structure that contains the rectangle (in logical coordinates) in which the text is to be formatted.
uFormat
[in] Specifies the method of formatting the text. This parameter can be one or more of the following values.
Value | Description
DT_BOTTOM | Justifies the text to the bottom of the rectangle. This value is used only with the DT_SINGLELINE value.
DT_CALCRECT | Determines the width and height of the rectangle. If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the lpRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER | Centers text horizontally in the rectangle.
DT_EDITCONTROL | Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS For displayed text, if the end of a string does not fit in the rectangle, it is truncated and ellipses are added. If a word that is not at the end of the string goes beyond the limits of the rectangle, it is truncated without ellipses.

The string is not modified unless the DT_MODIFYSTRING flag is specified.

Compare with DT_PATH_ELLIPSIS and DT_WORD_ELLIPSIS.
DT_EXPANDTABS | Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
DT_EXTERNALLEADING | Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_HIDEPREFIX Windows 2000 or later: Ignores the ampersand (&) prefix character in the text. The letter that follows will not be underlined, but other mnemonic-prefix characters are still processed. For example:
input string:    "A&bc&&d"
normal:          "Abc&d"
DT_HIDEPREFIX:   "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.
DT_INTERNAL | Uses the system font to calculate text metrics.
DT_LEFT | Aligns text to the left.
DT_MODIFYSTRING | Modifies the specified string to match the displayed text. This value has no effect unless DT_END_ELLIPSIS or DT_PATH_ELLIPSIS is specified.
DT_NOCLIP | Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used.
DT_NOFULLWIDTHCHARBREAK | Windows 98/Me, Windows 2000 or later: Prevents a line break at a DBCS (double-wide character string), so that the line breaking rule is equivalent to SBCS strings. For example, this can be used in Korean windows, for more readability of icon labels. This value has no effect unless DT_WORDBREAK is specified.
DT_NOPREFIX Turns off processing of prefix characters. Normally, DrawText interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. For example,
input string:   "A&bc&&d"
normal:         "Abc&d"
DT_NOPREFIX:    "A&bc&&d"

Compare with DT_HIDEPREFIX and DT_PREFIXONLY.
DT_PATH_ELLIPSIS For displayed text, replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash.

The string is not modified unless the DT_MODIFYSTRING flag is specified.

Compare with DT_END_ELLIPSIS and DT_WORD_ELLIPSIS.
DT_PREFIXONLY Windows 2000 or later: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any other characters in the string. For example,
input string:    "A&bc&&d"
normal:          "Abc&d"
DT_PREFIXONLY:   " _   "

Compare with DT_HIDEPREFIX and DT_NOPREFIX.
DT_RIGHT | Aligns text to the right.
DT_RTLREADING | Layout in right-to-left reading order for bi-directional text when the font selected into the hdc is a Hebrew or Arabic font. The default reading order for all text is left-to-right.
DT_SINGLELINE | Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TABSTOP | Sets tab stops. Bits 15–8 (high-order byte of the low-order word) of the uFormat parameter specify the number of characters for each tab. The default number of characters per tab is eight.The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.
DT_TOP | Justifies the text to the top of the rectangle.
DT_VCENTER | Centers text vertically. This value is used only with the DT_SINGLELINE value.
DT_WORDBREAK | Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the lpRect parameter. A carriage return-line feed sequence also breaks the line.
DT_WORD_ELLIPSIS Truncates any word that does not fit in the rectangle and adds ellipses.

Compare with DT_END_ELLIPSIS and DT_PATH_ELLIPSIS.

Return Values

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from lpRect->top to the bottom of the drawn text

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The DrawText 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 it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

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

The DrawText function supports only fonts whose escapement and orientation are both zero.

The text alignment mode for the device context must include the TA_LEFT, TA_TOP, and TA_NOUPDATECP flags.

For an example, see Displaying Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, DrawTextEx, GrayString, TabbedTextOut, TextOut, RECT


DrawTextEx

The DrawTextEx function draws formatted text in the specified rectangle.

int DrawTextEx(
  HDC hdc,                     // handle to DC
  LPTSTR lpchText,             // text to draw
  int cchText,                 // length of text to draw
  LPRECT lprc,                 // rectangle coordinates
  UINT dwDTFormat,             // formatting options
  LPDRAWTEXTPARAMS lpDTParams  // more formatting options
);

Parameters

hdc
[in] Handle to the device context in which to draw.
lpchText
[in/out] Pointer to the string that contains the text to draw. The string must be null-terminated if the cchText parameter is –1.

If dwDTFormat includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.

cchText
[in] Specifies the length of the string specified by the lpchText parameter. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs. If the string is null-terminated, this parameter can be –1 to calculate the length.

Windows 95/98/Me: This number may not exceed 8192.

lprc
[in/out] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted.
dwDTFormat
[in] Specifies formatting options. This parameter can be one or more of the following values.
Value | Meaning
DT_BOTTOM | Justifies the text to the bottom of the rectangle. This value is used only with the DT_SINGLELINE value.
DT_CALCRECT | Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextEx uses the width of the rectangle pointed to by the lprc parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextEx modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextEx returns the height of the formatted text, but does not draw the text.
DT_CENTER | Centers text horizontally in the rectangle.
DT_EDITCONTROL | Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS For displayed text, replaces the end of a string with ellipses so that the result fits in the specified rectangle. Any word (not at the end of the string) that goes beyond the limits of the rectangle is truncated without ellipses. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Compare with DT_PATH_ELLIPSIS and DT_WORD_ELLIPSIS.
DT_EXPANDTABS | Expands tab characters. The default number of characters per tab is eight.
DT_EXTERNALLEADING | Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_HIDEPREFIX Windows 2000 or later: Ignores the ampersand (&) prefix character in the text. The letter that follows will not be underlined, but other mnemonic-prefix characters are still processed.

Example:

input string: "A&bc&&d"
normal: "Abc&d"

HIDEPREFIX: "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.
DT_INTERNAL | Uses the system font to calculate text metrics.
DT_LEFT | Aligns text to the left.
DT_MODIFYSTRING | Modifies the specified string to match the displayed text. This value has no effect unless DT_END_ELLIPSIS or DT_PATH_ELLIPSIS is specified.
DT_NOCLIP | Draws without clipping. DrawTextEx is somewhat faster when DT_NOCLIP is used.
DT_NOFULLWIDTHCHARBREAK | Windows 98/Me, Windows 2000 or later: Prevents a line break at a DBCS (double-wide character string), so that the line-breaking rule is equivalent to SBCS strings. For example, this can be used in Korean windows, for more readability of icon labels. This value has no effect unless DT_WORDBREAK is specified.
DT_NOPREFIX | Turns off processing of prefix characters. Normally, DrawTextEx interprets the ampersand (&) mnemonic-prefix character as a directive to underscore the character that follows, and the double-ampersand (&&) mnemonic-prefix characters as a directive to print a single ampersand. By specifying DT_NOPREFIX, this processing is turned off. Compare with DT_HIDEPREFIX and DT_PREFIXONLY
DT_PATH_ELLIPSIS For displayed text, replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Compare with DT_END_ELLIPSIS and DT_WORD_ELLIPSIS.
DT_PREFIXONLY Windows 2000 or later: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any character in the string.

Example:

input string: "A&bc&&d"
normal: "Abc&d"

PREFIXONLY: " "

Compare with DT_NOPREFIX and DT_HIDEPREFIX.
DT_RIGHT | Aligns text to the right.
DT_RTLREADING | Layout in right-to-left reading order for bi-directional text when the font selected into the hdc is a Hebrew or Arabic font. The default reading order for all text is left-to-right.
DT_SINGLELINE | Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TABSTOP | Sets tab stops. The DRAWTEXTPARAMS structure pointed to by the lpDTParams parameter specifies the number of average character widths per tab stop.
DT_TOP | Justifies the text to the top of the rectangle.
DT_VCENTER | Centers text vertically. This value is used only with the DT_SINGLELINE value.
DT_WORDBREAK | Breaks words. Lines are automatically broken between words if a word extends past the edge of the rectangle specified by the lprc parameter. A carriage return-line feed sequence also breaks the line.
DT_WORD_ELLIPSIS Truncates any word that does not fit in the rectangle and adds ellipses.

Compare with DT_END_ELLIPSIS and DT_PATH_ELLIPSIS.

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

Return Values

If the function succeeds, the return value is the text height in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from lprc->top to the bottom of the drawn text

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The DrawTextEx function supports only fonts whose escapement and orientation are both zero.

The text alignment mode for the device context must include the TA_LEFT, TA_TOP, and TA_NOUPDATECP flags.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, DrawText, DRAWTEXTPARAMS


EnumFontFamExProc

The EnumFontFamExProc function is an application defined–callback function used with the EnumFontFamiliesEx function. It is used to process the fonts. It is called once for each enumerated font. The FONTENUMPROC type defines a pointer to this callback function. EnumFontFamExProc is a placeholder for the application defined–function name.

int CALLBACK EnumFontFamExProc(
  ENUMLOGFONTEX *lpelfe,    // logical-font data
  NEWTEXTMETRICEX *lpntme,  // physical-font data
  DWORD FontType,           // type of font
  LPARAM lParam             // application-defined data
);

Parameters

lpelfe
[in] Pointer to an ENUMLOGFONTEX structure that contains information about the logical attributes of the font.

Windows 2000 or later: This can be an ENUMLOGFONTEXDV structure.

lpntme
[in] Pointer to a structure that contains information about the physical attributes of a font. The function uses the NEWTEXTMETRICEX structure for TrueType fonts; and the TEXTMETRIC structure for other fonts.

Windows 2000 or later: This can be an ENUMTEXTMETRIC structure.

FontType
[in] Specifies the type of the font. This parameter can be a combination of these values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE

lParam
[in] Specifies the application-defined data passed by the EnumFontFamiliesEx function.

Return Values

The return value must be a nonzero value to continue enumeration; to stop enumeration, the return value must be zero.

Remarks

An application must register this callback function by passing its address to the EnumFontFamiliesEx function.

Unlike the EnumFontFamProc callback function, EnumFontFamExProc receives extended information about a font. The ENUMLOGFONTEX structure includes the localized name of the script (character set) and the NEWTEXTMETRICEX structure includes a font-coverage signature.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFontFamiliesEx, EnumFontFamProc, ENUMLOGFONTEX, ENUMLOGFONTEXDV, ENUMTEXTMETRIC, NEWTEXTMETRICEX, TEXTMETRIC


EnumFontFamilies

The EnumFontFamilies function enumerates the fonts in a specified font family that are available on a specified device.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the EnumFontFamiliesEx function.

int EnumFontFamilies(
  HDC hdc,                        // handle to DC
  LPCTSTR lpszFamily,             // font family
  FONTENUMPROC lpEnumFontFamProc, // callback function
  LPARAM lParam                   // additional data
);

Parameters

hdc
[in] Handle to the device context.
lpszFamily
[in] Pointer to a null-terminated string that specifies the family name of the desired fonts. If lpszFamily is NULL, EnumFontFamilies selects and enumerates one font of each available type family.
lpEnumFontFamProc
[in] Point to the application defined–callback function. For information, see EnumFontFamProc.
lParam
[in] Pointer to application-supplied data. The data is passed to the callback function along with the font information.

Return Values

The return value is the last value returned by the callback function. Its meaning is implementation specific.

Remarks

For each font having the typeface name specified by the lpszFamily parameter, the EnumFontFamilies function retrieves information about that font and passes it to the function pointed to by the lpEnumFontFamProc parameter. The application defined–callback function can process the font information as desired. Enumeration continues until there are no more fonts or the callback function returns zero.

The fonts for many East Asian languages have two typeface names: an English name and a localized name. EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

For examples, see Enumerating the Installed Fonts.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFonts, EnumFontFamiliesEx, EnumFontFamProc


EnumFontFamiliesEx

The EnumFontFamiliesEx function enumerates all fonts in the system that match the font characteristics specified by the LOGFONT structure. EnumFontFamiliesEx enumerates fonts based on typeface name, character set, or both.

int EnumFontFamiliesEx(
  HDC hdc,                          // handle to DC
  LPLOGFONT lpLogfont,              // font information
  FONTENUMPROC lpEnumFontFamExProc, // callback function
  LPARAM lParam,                    // additional data
  DWORD dwFlags                     // not used; must be 0
);

Parameters

hdc
[in] Handle to the device context.
lpLogfont
[in] Pointer to a LOGFONT structure that contains information about the fonts to enumerate. The function examines the following members.
Member | Description
lfCharset | If set to DEFAULT_CHARSET, the function enumerates all fonts in all character sets. If set to a valid character set value, the function enumerates only fonts in the specified character set.
lfFaceName | If set to an empty string, the function enumerates one font in each available typeface name. If set to a valid typeface name, the function enumerates all fonts with the specified name.
lfPitchAndFamily | Must be set to zero for all language versions of the operating system.

lpEnumFontFamExProc
[in] Pointer to the application defined–callback function. For more information, see the EnumFontFamExProc function.
lParam
[in] Specifies an application–defined value. The function passes this value to the callback function along with font information.
dwFlags
This parameter is not used and must be zero.

Return Values

The return value is the last value returned by the callback function. This value depends on which font families are available for the specified device.

Remarks

The EnumFontFamiliesEx function does not use tagged typeface names to identify character sets. Instead, it always passes the correct typeface name and a separate character set value to the callback function. The function enumerates fonts based on the the values of the lfCharset and lfFacename members in the LOGFONT structure.

As with EnumFontFamilies, EnumFontFamiliesEx enumerates all font styles. Not all styles of a font cover the same character sets. For example, Fontorama Bold might contain ANSI, Greek, and Cyrillic characters, but Fontorama Italic might contain only ANSI characters. For this reason, it's best not to assume that a specified font covers a specific character set, even if it is the ANSI character set. The following table shows the results of various combinations of values for lfCharSet and lfFaceName.

Values | Meaning
lfCharSet = DEFAULT_CHARSET lfFaceName = '\0' | Enumerates all fonts in all character sets.
lfCharSet = DEFAULT_CHARSET lfFaceName = a specific font | Enumerates all character sets and styles in a specific font.
lfCharSet =a specific character set lfFaceName = '\0' | Enumerates all styles of all fonts in the specific character set.
lfCharSet =a specific character set lfFaceName = a specific font | Enumerates all styles of a font in a specific character set.

The following code sample shows how these values are used.

//to enumerate all styles and charsets of all fonts:
lf.lfFaceName[0] = '\0';
lf.lfCharSet = DEFAULT_CHARSET;

//to enumerate all styles and character sets of the Arial font:
lstrcpy( (LPSTR)&lf.lfFaceName, "Arial" );
lf.lfCharSet = DEFAULT_CHARSET;

//to enumerate all styles of all fonts for the ANSI character set
lf.lfFaceName[0] = '\0';
lf.lfCharSet = ANSI_CHARSET;

//to enumerate all styles of Arial font that cover the ANSI charset
lstrcpy( (LPSTR)&lf.lfFaceName, "Arial" );
lf.lfCharSet = ANSI_CHARSET;

The callback functions for EnumFontFamilies and EnumFontFamiliesEx are very similar. The main difference is that the ENUMLOGFONTEX structure includes a script field.

Note, based on the values of lfCharSet and lfFaceName, EnumFontFamiliesEx will enumerate the same font as many times as there are distinct character sets in the font. This can create an extensive list of fonts which can be burdensome to a user. For example, the Century Schoolbook font can appear for the Baltic, Western, Greek, Turkish, and Cyrillic character sets. To avoid this, an application should filter the list of fonts.

The fonts for many East Asian languages have two typeface names: an English name and a localized name. EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFontFamExProc, EnumFonts, EnumFontFamilies, LOGFONT


EnumFontFamProc

The EnumFontFamProc function is an application defined–callback function used with the EnumFontFamilies function. It receives data describing the available fonts. The FONTENUMPROC type defines a pointer to this callback function. EnumFontFamProc is a placeholder for the application defined–function name.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should call the EnumFontFamiliesEx function.

int CALLBACK EnumFontFamProc(
  ENUMLOGFONT *lpelf,    // logical-font data
  NEWTEXTMETRIC *lpntm,  // physical-font data
  DWORD FontType,        // type of font
  LPARAM lParam          // application-defined data
);

Parameters

lpelf
[in] Pointer to an ENUMLOGFONT structure that contains information about the logical attributes of the font. This structure is locally defined.

Windows 2000 or later: This can be an ENUMLOGFONTEXDV structure.

lpntm
[in] Pointer to a NEWTEXTMETRIC structure that contains information about the physical attributes of the font, if the font is a TrueType font. If the font is not a TrueType font, this parameter is a pointer to a TEXTMETRIC structure.

Windows 2000 or later: This can be an ENUMTEXTMETRIC structure.

FontType
[in] Specifies the type of the font. This parameter can be a combination of the following values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE

lParam
[in] Pointer to the application-defined data passed by the EnumFontFamilies function.

Return Values

The return value must be a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register this callback function by passing its address to the EnumFontFamilies function.

The AND (&) operator can be used with the RASTER_FONTTYPE, DEVICE_FONTTYPE, and TRUETYPE_FONTTYPE constants to determine the font type. If the RASTER_FONTTYPE bit is set, the font is a raster font. If the TRUETYPE_FONTTYPE bit is set, the font is a TrueType font. If neither bit is set, the font is a vector font. DEVICE_FONTTYPE is set when a device (for example, a laser printer) supports downloading TrueType fonts or when the font is a device-resident font; it is zero if the device is a display adapter, dot-matrix printer, or other raster device. An application can also use DEVICE_FONTTYPE to distinguish graphics device interface (GDI)-supplied raster fonts from device-supplied fonts. GDI can simulate bold, italic, underline, and strikeout attributes for GDI-supplied raster fonts, but not for device-supplied fonts.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFontFamilies, ENUMLOGFONT, ENUMLOGFONTEXDV, ENUMTEXTMETRIC, NEWTEXTMETRIC, TEXTMETRIC


EnumFonts

The EnumFonts function enumerates the fonts available on a specified device. For each font with the specified typeface name, the EnumFonts function retrieves information about that font and passes it to the application defined–callback function. This callback function can process the font information as desired. Enumeration continues until there are no more fonts or the callback function returns zero.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the EnumFontFamiliesEx function.

int EnumFonts(
  HDC hdc,                  // handle to DC
  LPCTSTR lpFaceName,       // font typeface name
  FONTENUMPROC lpFontFunc,  // callback function
  LPARAM lParam             // application-supplied data
);

Parameters

hdc
[in] Handle to the device context.
lpFaceName
[in] Pointer to a null-terminated string that specifies the typeface name of the desired fonts. If lpFaceName is NULL, EnumFonts randomly selects and enumerates one font of each available typeface.
lpFontFunc
[in] Pointer to the application defined–callback function. For more information, see EnumFontsProc.
lParam
[in] Pointer to any application-defined data. The data is passed to the callback function along with the font information.

Return Values

The return value is the last value returned by the callback function. Its meaning is defined by the application.

Remarks

Use EnumFontFamiliesEx instead of EnumFonts. The EnumFontFamiliesEx function differs from the EnumFonts function in that it retrieves the style names associated with a TrueType font. With EnumFontFamiliesEx, you can retrieve information about font styles that cannot be enumerated using the EnumFonts function.

The fonts for many East Asian languages have two typeface names: an English name and a localized name. EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx return the English typeface name if the system locale does not match the language of the font.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFontFamilies, EnumFontFamiliesEx EnumFontsProc, GetDeviceCaps


EnumFontsProc

The EnumFontsProc function is an application defined–callback function that processes font data from the EnumFonts function. The FONTENUMPROC type defines a pointer to this callback function. EnumFontsProc is a placeholder for the application defined–function name.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should call the EnumFontFamiliesEx function.

int CALLBACK EnumFontsProc(
  CONST LOGFONT *lplf,     // logical-font data
  CONST TEXTMETRIC *lptm,  // physical-font data
  DWORD dwType,            // font type
  LPARAM lpData            // application-defined data
);

Parameters

lplf
[in] Pointer to a LOGFONT structure that contains information about the logical attributes of the font.

Windows 2000 or later: This can be an ENUMLOGFONTEXDV structure.

lptm
[in] Pointer to a TEXTMETRIC structure that contains information about the physical attributes of the font.

Windows 2000 or later: This can be an ENUMTEXTMETRIC structure.

dwType
[in] Specifies the type of the font. This parameter can be a combination of the following values:

DEVICE_FONTTYPE
RASTER_FONTTYPE
TRUETYPE_FONTTYPE

lpData
[in] Pointer to the application-defined data passed by EnumFonts.

Return Values

The return value must be a nonzero value to continue enumeration; to stop enumeration, it must be zero.

Remarks

The AND (&) operator can be used with the RASTER_FONTTYPE and DEVICE_FONTTYPE constants to determine the font type. The RASTER_FONTTYPE bit of the FontType parameter specifies whether the font is a raster or vector font. If the bit is one, the font is a raster font; if zero, it is a vector font. The DEVICE_FONTTYPE bit of FontType specifies whether the font is a device-based or graphics device interface (GDI)-based font. If the bit is one, the font is a device-based font; if zero, it is a GDI-based font.

If the device is capable of text transformations (scaling, italicizing, and so on) only the base font is enumerated. The user must inquire into the device's text-transformation abilities to determine which additional fonts are available directly from the device.

An application must register the EnumFontsProc function by passing its address to the EnumFonts function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI prototypes.

See Also

Fonts and Text Overview, Font and Text Functions, EnumFonts, ENUMLOGFONTEXDV, ENUMTEXTMETRIC, LOGFONT, TEXTMETRIC


ExtTextOut

The ExtTextOut function draws text using the currently selected font, background color, and text color. You can optionally provide dimensions to be used for clipping, opaquing, or both.

BOOL ExtTextOut(
  HDC hdc,          // handle to DC
  int X,            // x-coordinate of reference point
  int Y,            // y-coordinate of reference point
  UINT fuOptions,   // text-output options
  CONST RECT* lprc, // optional dimensions
  LPCTSTR lpString, // string
  UINT cbCount,     // number of characters in string
  CONST INT* lpDx   // array of spacing values
);

Parameters

hdc
[in] Handle to the device context.
X
[in] Specifies the logical x-coordinate of the reference point used to position the string.
Y
[in] Specifies the logical y-coordinate of the reference point used to position the string.
fuOptions
[in] Specifies how to use the application-defined rectangle. This parameter can be one or more of the following values.
Value | Meaning
ETO_CLIPPED | The text will be clipped to the rectangle.
ETO_GLYPH_INDEX The lpString array refers to an array returned from GetCharacterPlacement and should be parsed directly by GDI as no further language-specific processing is required. Glyph indexing only applies to TrueType fonts, but the flag can be used for bitmap and vector fonts to indicate that no further language processing is necessary and GDI should process the string directly. Note that all glyph indexes are 16-bit values even though the string is assumed to be an array of 8-bit values for raster fonts.

For ExtTextOutW, the glyph indexes are saved to a metafile. However, to display the correct characters the metafile must be played back using the same font. For ExtTextOutA, the glyph indexes are not saved.
ETO_NUMERICSLATIN | To display numbers, use European digits.
ETO_NUMERICSLOCAL | To display numbers, use digits appropriate to the locale.
ETO_OPAQUE | The current background color should be used to fill the rectangle.
ETO_PDY | When this is set, the array pointed to by lpDx contains pairs of values. The first value of each pair is, as usual, the distance between origins of adjacent character cells, but the second value is the displacement along the vertical direction of the font.
ETO_RTLREADING | Middle-Eastern Windows: If this value is specified and a Hebrew or Arabic font is selected into the device context, the string is output using right-to-left reading order. If this value is not specified, the string is output in left-to-right order. The same effect can be achieved by setting the TA_RTLREADING value in SetTextAlign. This value is preserved for backward compatability.

The ETO_GLYPH_INDEX and ETO_RTLREADING values cannot be used together. Because ETO_GLYPH_INDEX implies that all language processing has been completed, the function ignores the ETO_RTLREADING flag if also specified.

lprc
[in] Pointer to an optional RECT structure that specifies the dimensions of a rectangle that is used for clipping, opaquing, or both.
lpString
[in] Pointer to a string that specifies the text to be drawn. The string does not need to be zero-terminated, since cbCount specifies the length of the string.
cbCount
[in] Specifies the length of the string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

lpDx
[in] Pointer to an optional array of values that indicate the distance between origins of adjacent character cells. For example, lpDx[i] logical units separate the origins of character cell i and character cell i + 1.

Return Values

If the string is drawn, the return value is nonzero. However, if the ANSI version of ExtTextOut is called with ETO_GLYPH_INDEX, the function returns TRUE even though the function does nothing.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Although not true in general, Windows 95/98 supports the Unicode version of this function as well as the ANSI version.

The current text-alignment settings for the specified device context determine how the reference point is used to position the text. The text-alignment settings are retrieved by calling the GetTextAlign function. The text-alignment settings are altered by calling the SetTextAlign function.

If the lpDx parameter is NULL, the ExtTextOut function uses the default spacing between characters. The character-cell origins and the contents of the array pointed to by the lpDx parameter are specified in logical units. A character-cell origin is defined as the upper-left corner of the character cell.

By default, the current position is not used or updated by this function. However, an application can call the SetTextAlign function with the fMode parameter set to TA_UPDATECP to permit the system to use and update the current position each time the application calls ExtTextOut for a specified device context. When this flag is set, the system ignores the X and Y parameters on subsequent ExtTextOut calls.

For the ANSI version of ExtTextOut, the lpDx array has the same number of INT values as there are bytes in lpString. For DBCS characters, you can apportion the dx in the lpDx entries between the lead byte and the trail byte, as long as the sum of the two bytes adds up to the desired dx. For DBCS characters with the Unicode version of ExtTextOut, each Unicode glyph gets a single pdx entry.

Note, the alpDx values from GetTextExtentExPoint are not the same as the lpDx values for ExtTextOut. To use the alpDx values in lpDx, you must first process them.

For an example, see Setting Fonts for Menu-Item Text Strings.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextAlign, RECT, SetBkColor, SelectObject, SetTextAlign, SetTextColor


GetAspectRatioFilterEx

The GetAspectRatioFilterEx function retrieves the setting for the current aspect-ratio filter.

BOOL GetAspectRatioFilterEx(
  HDC hdc,               // handle to DC
  LPSIZE lpAspectRatio   // aspect-ratio filter
);

Parameters

hdc
[in] Handle to a device context.
lpAspectRatio
[out] Pointer to a SIZE structure that receives the current aspect-ratio filter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The aspect ratio is the ratio formed by the width and height of a pixel on a specified device.

The system provides a special filter, the aspect-ratio filter, to select fonts that were designed for a particular device. An application can specify that the system should only retrieve fonts matching the specified aspect ratio by calling the SetMapperFlags function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, SetMapperFlags, SIZE


GetCharABCWidths

The GetCharABCWidths function retrieves the widths, in logical units, of consecutive characters in a specified range from the current TrueType font. This function succeeds only with TrueType fonts.

BOOL GetCharABCWidths(
  HDC hdc,         // handle to DC
  UINT uFirstChar, // first character in range
  UINT uLastChar,  // last character in range
  LPABC lpabc      // array of character widths
);

Parameters

hdc
[in] Handle to the device context.
uFirstChar
[in] Specifies the first character in the group of consecutive characters from the current font.
uLastChar
[in] Specifies the last character in the group of consecutive characters from the current font.
lpabc
[out] Pointer to an array of ABC structures that receives the character widths. This array must contain at least as many ABC structures as there are characters in the range specified by the uFirstChar and uLastChar parameters.

Return Values

If the function succeeds, the return value is nonzero

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

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

When the GetCharABCWidths 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 use the value stored in the otmEMSquare member of a OUTLINETEXTMETRIC structure. This value can be retrieved by calling the GetOutlineTextMetrics function.

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

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharWidth, GetOutlineTextMetrics, OUTLINETEXTMETRIC, ABC


GetCharABCWidthsFloat

The GetCharABCWidthsFloat function retrieves the widths, in logical units, of consecutive characters in a specified range from the current font.

BOOL GetCharABCWidthsFloat(
  HDC hdc,            // handle to DC
  UINT iFirstChar,    // first character in range
  UINT iLastChar,     // last character in range
  LPABCFLOAT lpABCF   // array of character widths
);

Parameters

hdc
[in] Handle to the device context.
iFirstChar
[in] Specifies the code point of the first character in the group of consecutive characters where the ABC widths are sought.
iLastChar
[in] Specifies the code point of the last character in the group of consecutive characters where the ABC widths are sought. This range is inclusive. An error is returned if the specified last character precedes the specified first character.
lpABCF
[out] Pointer to an array of ABCFLOAT structures that receives the character widths.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Unlike the GetCharABCWidths function that returns widths only for TrueType fonts, the GetCharABCWidthsFloat function retrieves widths for any font. The widths returned by this function are in the IEEE floating-point format.

If the current world-to-device transformation is not identified, the returned widths may be noninteger values, even if the corresponding values in the device space are integers.

A spacing is the distance added to the current position before placing the glyph. B spacing is the width of the black part of the glyph. C spacing is the distance added to the current position to provide white space to the right of the glyph. The total advanced width is specified by A+B+C.

The ABC spaces are measured along the character base line of the selected font.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, ABCFLOAT, GetCharABCWidths, GetCharWidth, GetCharWidthFloat


GetCharABCWidthsI

The GetCharABCWidthsI function retrieves the widths, in logical units, of consecutive glyph indices in a specified range from the current TrueType font. This function succeeds only with TrueType fonts.

BOOL GetCharABCWidthsI(
  HDC hdc,         // handle to DC
  UINT giFirst,    // first glyph index in range
  UINT cgi,        // count of glyph indices in range
  LPWORD pgi,      // array of glyph indices
  LPABC lpabc      // array of character widths
);

Parameters

hdc
[in] Handle to the device context.
giFirst
[in] 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
[in] Specifies the number of glyph indices.
pgi
[in] Pointer to an array that contains glyph indices. If this parameter is NULL, the giFirst parameter is used instead. The cgi parameter specifies the number of glyph indices in this array.
lpabc
[out] Pointer to an array of ABC structures that receives the character widths. This array must contain at least as many ABC structures as there are glyph indices specified by the cgi parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

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

When the GetCharABCWidthsI 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 use the value stored in the otmEMSquare member of a OUTLINETEXTMETRIC structure. This value can be retrieved by calling the GetOutlineTextMetrics function.

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

To retrieve the widths of glyph indices in non-TrueType fonts, applications should use the GetCharWidthI function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharWidth, GetOutlineTextMetrics, OUTLINETEXTMETRIC, ABC


GetCharacterPlacement

The GetCharacterPlacement function retrieves information about a character string, such as character widths, caret positioning, ordering within the string, and glyph rendering. The type of information returned depends on the dwFlags parameter and is based on the currently selected font in the specified display context. The function copies the information to the specified GCP_RESULTS structure or to one or more arrays specified by the structure.

This function has been superseded by the functionality of the Uniscribe module. For more information, see Uniscribe.

DWORD GetCharacterPlacement(
  HDC hdc,                  // handle to DC
  LPCTSTR lpString,         // character string
  int nCount,               // number of characters
  int nMaxExtent,           // maximum extent for string
  LPGCP_RESULTS lpResults,  // placement result
  DWORD dwFlags             // placement options
);

Parameters

hdc
[in] Handle to the device context.
lpString
[in] Pointer to the character string to process.
nCount
[in] Specifies the length of the string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

nMaxExtent
[in] 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
[in/out] Pointer to a GCP_RESULTS structure that receives the results of the function.
dwFlags
[in] Specifies how to process the string into the required arrays. This parameter can be one or more of the following values.
Value | Meaning
GCP_CLASSIN | Specifies that the lpClass array contains preset classifications for characters. The classifications may be the same as on output. If the particular classification for a character is not known, the corresponding location in the array must be set to zero. for more information about the classifications, see GCP_RESULTS. This is useful only if GetFontLanguageInfo returned the GCP_REORDER flag.
GCP_DIACRITIC Determines how diacritics in the string are handled. If this value is not set, diacritics are treated as zero-width characters. For example, a Hebrew string may contain diacritics, but you may not want to display them.

Use GetFontLanguageInfo to determine whether a font supports diacritics. If it does, you can use or not use the GCP_DIACRITIC flag in the call to GetCharacterPlacement, depending on the needs of your application.

GCP_DISPLAYZWG | For languages that need reordering or different glyph shapes depending on the positions of the characters within a word, nondisplayable characters often appear in the code page. For example, in the Hebrew code page, there are Left-To-Right and Right-To-Left markers, to help determine the final positioning of characters within the output strings. Normally these are not displayed and are removed from the lpGlyphs and lpDx arrays. You can use the GCP_DISPLAYZWG flag to display these characters.
GCP_GLYPHSHAPE | Specifies that some or all characters in the string are to be displayed using shapes other than the standard shapes defined in the currently selected font for the current code page. Some languages, such as Arabic, cannot support glyph creation unless this value is specified. As a general rule, if GetFontLanguageInfo returns this value for a string, this value must be used with GetCharacterPlacement.
GCP_JUSTIFY | Adjusts the extents in the lpDx array so that the string length is the same as nMaxExtent. GCP_JUSTIFY may only be used in conjunction with GCP_MAXEXTENT.
GCP_KASHIDA Use Kashidas as well as, or instead of, adjusted extents to modify the length of the string so that it is equal to the value specified by nMaxExtent. In the lpDx array, a Kashida is indicated by a negative justification index. GCP_KASHIDA may be used only in conjunction with GCP_JUSTIFY and only if the font (and language) support Kashidas. Use GetFontLanguageInfo to determine whether the current font supports Kashidas.

Using Kashidas to justifiy the string can result in the number of glyphs required being greater than the number of characters in the input string. Because of this, when Kashidas are used, the application cannot assume that setting the arrays to be the size of the input string will be sufficient. (The maximum possible will be approximately dxPageWidth/dxAveCharWidth, where dxPageWidth is the width of the document and dxAveCharWidth is the average character width as returned from a GetTextMetrics call).

Note that just because GetFontLanguageInfo returns the GCP_KASHIDA flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.
GCP_LIGATE Use ligations wherever characters ligate. A ligation occurs where one glyph is used for two or more characters. For example, the letters a and e can ligate to æ. For this to be used, however , both the language support and the font must support the required glyphs (the example will not be processed by default in English).

Use GetFontLanguageInfo to determine whether the current font supports ligation. If it does and a specific maximum is required for the number of characters that will ligate, set the number in the first element of the lpGlyphs array. If normal ligation is required, set this value to zero. If GCP_LIGATE is not specified, no ligation will take place. See GCP_RESULTS for more information.

If the GCP_REORDER value is usually required for the character set but is not specified, the output will be meaningless unless the string being passed in is already in visual ordering (that is, the result that gets put into lpGcpResults->lpOutString in one call to GetCharacterPlacement is the input string of a second call).

Note that just because GetFontLanguageInfo returns the GCP_LIGATE flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.

GCP_MAXEXTENT | Compute extents of the string only as long as the resulting extent, in logical units, does not exceed the values specified by the nMaxExtent parameter.
GCP_NEUTRALOVERRIDE | Certain languages only. Override the normal handling of neutrals and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICOVERRIDE | Certain languages only. Override the normal handling of numerics and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICSLATIN | Arabic/Thai only. Use standard Latin glyphs for numbers and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_NUMERICSLOCAL | Arabic/Thai only. Use local glyphs for numeric characters and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_REORDER Reorder the string. Use for languages that are not SBCS and left-to-right reading order. If this value is not specified, the string is assumed to be in display order already.

If this flag is set for Semitic languages and the lpClass array is used, the first two elements of the array are used to specify the reading order beyond the bounds of the string. GCP_CLASS_PREBOUNDRTL and GCP_CLASS_PREBOUNDLTR can be used to set the order. If no preset order is required, set the values to zero. These values can be combined with other values if theGCPCLASSIN flag is set.

If the GCP_REORDER value is not specified, the lpString parameter is taken to be visual ordered for languages where this is used, and the lpOutString and lpOrder fields are ignored.

Use GetFontLanguageInfo to determine whether the current font supports reordering.
GCP_SYMSWAPOFF | Semitic languages only. Specifies that swappable characters are not reset. For example, in a right-to-left string, the '(' and ')' are not reversed.
GCP_USEKERNING Use kerning pairs in the font (if any) when creating the widths arrays. Use GetFontLanguageInfo to determine whether the current font supports kerning pairs.

Note that just because GetFontLanguageInfo returns the GCP_USEKERNING flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available. Most TrueType fonts have a kerning table, but you do not have to use it.

It is recommended that an application use the GetFontLanguageInfo function to determine whether the GCP_DIACRITIC, GCP_DBCS, GCP_USEKERNING, GCP_LIGATE, GCP_REORDER, GCP_GLYPHSHAPE, and GCP_KASHIDA values are valid for the currently selected font. If not valid, GetCharacterPlacement ignores the value.

The GCP_NODIACRITICS value is no longer defined and should not be used.

Return Values

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

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

GetCharacterPlacement ensures that an application can correctly process text regardless of the international setting and type of fonts available. Applications use this function before using the ExtTextOut function and in place of the GetTextExtentPoint32 function (and occasionally in place of the GetCharWidth32 and GetCharABCWidths functions).

Using GetCharacterPlacement to retrieve intercharacter spacing and index arrays is not always necessary unless justification or kerning is required. For non-Latin fonts, applications can improve the speed at which the ExtTextOut function renders text by using GetCharacterPlacement to retrieve the intercharacter spacing and index arrays before calling ExtTextOut. This is especially useful when rendering the same text repeatedly or when using intercharacter spacing to position the caret. If the lpGlyphs output array is used in the call to ExtTextOut, the ETO_GLYPH_INDEX flag must be set.

GetCharacterPlacement checks the lpOrder, lpDx, lpCaretPos, lpOutString, and lpGlyphs members of the GCP_RESULTS structure and fills the corresponding arrays if these members are not set to NULL. If GetCharacterPlacement cannot fill an array, it sets the corresponding member to NULL. To ensure retrieval of valid information, the application is responsible for setting the member to a valid address before calling the function and for checking the value of the member after the call. If the GCP_JUSTIFY or GCP_USEKERNING values are specified, the lpDx and/or lpCaretPos members must have valid addresses.

When computing justification, if the trailing characters in the string are spaces, the function reduces the length of the string and removes the spaces prior to computing the justification. If the array consists of only spaces, the function returns an error.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GCP_RESULTS, GetCharABCWidths, GetCharWidth32, GetFontLanguageInfo, GetStringTypeEx, GetTextExtentPoint32, GetTextMetrics


GetCharWidth

The GetCharWidth function retrieves the widths, in logical coordinates, of consecutive characters in a specified range from the current font.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should call the GetCharWidth32 function, which provides more accurate results.

BOOL GetCharWidth(
  HDC hdc,         // handle to DC
  UINT iFirstChar, // first character in range
  UINT iLastChar,  // last character in range
  LPINT lpBuffer   // buffer for widths
);

Parameters

hdc
[in] Handle to the device context.
iFirstChar
[in] Specifies the first character in the group of consecutive characters.
iLastChar
[in] Specifies the last character in the group of consecutive characters, which must not precede the specified first character.
lpBuffer
[out] Pointer to a buffer that receives the character widths.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The range is inclusive; that is, the returned widths include the widths of the characters specified by the iFirstChar and iLastChar parameters.

If a character does not exist in the current font, it is assigned the width of the default character.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth32, GetCharWidthFloat


GetCharWidth32

The GetCharWidth32 function retrieves the widths, in logical coordinates, of consecutive characters in a specified range from the current font.

BOOL GetCharWidth32(
  HDC hdc,          // handle to DC
  UINT iFirstChar,  // first character in range
  UINT iLastChar,   // last character in range
  LPINT lpBuffer    // buffer for widths
);

Parameters

hdc
[in] Handle to the device context.
iFirstChar
[in] Specifies the first character in the group of consecutive characters.
iLastChar
[in] Specifies the last character in the group of consecutive characters, which must not precede the specified first character.
lpBuffer
[out] Pointer to a buffer that receives the character widths.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The range is inclusive; that is, the returned widths include the widths of the characters specified by the iFirstChar and iLastChar parameters.

If a character does not exist in the current font, it is assigned the width of the default character.

For an example, see Displaying Keyboard Input.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidthFloat


GetCharWidthFloat

The GetCharWidthFloat function retrieves the fractional widths of consecutive characters in a specified range from the current font.

BOOL GetCharWidthFloat(
  HDC hdc,          // handle to DC
  UINT iFirstChar,  // first-character code point
  UINT iLastChar,   // last-character code point
  PFLOAT pxBuffer   // buffer for widths
);

Parameters

hdc
[in] Handle to the device context.
iFirstChar
[in] Specifies the code point of the first character in the group of consecutive characters.
iLastChar
[in] Specifies the code point of the last character in the group of consecutive characters.
pxBuffer
[out] Pointer to a buffer that receives the character widths.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The returned widths are in the 32-bit IEEE floating-point format. (The widths are measured along the base line of the characters.)

If the iFirstChar parameter specifies the letter a and the iLastChar parameter specifies the letter z, GetCharWidthFloat retrieves the widths of all lowercase characters.

If a character does not exist in the current font, it is assigned the width of the default character.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth32


GetCharWidthI

The GetCharWidthI function retrieves the widths, in logical coordinates, of consecutive glyph indices in a specified range from the current font.

BOOL GetCharWidthI(
  HDC hdc,         // handle to DC
  UINT giFirst,    // first glyph index in range
  UINT cgi,        // number of glyph indicies in range
  LPWORD pgi,      // array of glyph indices
  LPINT lpBuffer   // buffer for widths
);

Parameters

hdc
[in] Handle to the device context.
giFirst
[in] Specifies the first glyph index in the group of consecutive glyph indices.
cgi
[in] Specifies the number of glyph indices.
pgi
[in] Pointer to an array of glyph indices. If this parameter is not NULL, it is used instead of the giFirst parameter.
lpBuffer
[out] Pointer to a buffer that receives the widths.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The GetCharWidthI function processes a consecutive glyph indices if the pgi parameter is NULL with the giFirst parameter indicating the first glyph index to process and the cgi parameter indicating how many glyph indices to process. Otherwise the GetCharWidthI function processes the array of glyph indices pointed to by the pgi parameter with the cgi parameter indicating how many glyph indices to process.

If a character does not exist in the current font, it is assigned the width of the default character.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetCharABCWidths, GetCharABCWidthsFloat, GetCharWidth32, GetCharWidthFloat


GetFontData

The GetFontData function retrieves font metric data for a TrueType font.

DWORD GetFontData(
  HDC hdc,           // handle to DC
  DWORD dwTable,     // metric table name
  DWORD dwOffset,    // offset into table
  LPVOID lpvBuffer,  // buffer for returned data
  DWORD cbData       // length of data
);

Parameters

hdc
[in] Handle to the device context.
dwTable
[in] Specifies the name of a font metric table from which the font data is to be retrieved. This parameter can identify one of the metric tables documented in the TrueType Font Files specification published by Microsoft Corporation. If this parameter is zero, the information is retrieved starting at the beginning of the font file.
dwOffset
[in] Specifies the offset from the beginning of the font metric table to the location where the function should begin retrieving information. If this parameter is zero, 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, an error occurs.
lpvBuffer
[out] Pointer to a buffer that receives the font information. If this parameter is NULL, the function returns the size of the buffer required for the font data.
cbData
[in] Specifies the length, in bytes, of the information to be retrieved. If this parameter is zero, GetFontData returns the size of the data specified in the dwTable parameter.

Return Values

If the function succeeds, the return value is the number of bytes returned.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can sometimes use the GetFontData function to save a TrueType font with a document. To do this, the application determines whether the 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 embedding is permitted, the application can retrieve the entire font file, specifying zero for the dwTable, dwOffset, and cbData parameters.

If an application attempts to use this function to retrieve information for a non-TrueType font, an error occurs.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextMetrics, OUTLINETEXTMETRIC


GetFontLanguageInfo

The GetFontLanguageInfo function returns information about the currently selected font for the specified display context. Applications typically use this information and the GetCharacterPlacement function to prepare a character string for display.

DWORD GetFontLanguageInfo(
  HDC hdc  // handle to DC
);

Parameters

hdc
[in] Handle to a display device context.

Return Values

The return value identifies characteristics of the currently selected font. The function returns 0 if the font is "normalized" and can be treated as a simple Latin font; it returns GCP_ERROR if an error occurs. Otherwise, the function returns a combination of the following values.

Value | Meaning
GCP_DBCS | The character set is DBCS.
GCP_DIACRITIC | The font/language contains diacritic glyphs.
FLI_GLYPHS | The font contains extra glyphs not normally accessible using the code page. Use GetCharacterPlacement to access the glyphs. This value is for information only and is not intended to be passed to GetCharacterPlacement.
GCP_GLYPHSHAPE | The font/language contains multiple glyphs per code point or per code point combination (supports shaping and/or ligation), and the font contains advanced glyph tables to provide extra glyphs for the extra shapes. If this value is specified, the lpGlyphs array must be used with the GetCharacterPlacement function and the ETO_GLYPHINDEX value must be passed to the ExtTextOut function when the string is drawn.
GCP_KASHIDA | The font/ language permits Kashidas.
GCP_LIGATE | The font/language contains ligation glyphs which can be substituted for specific character combinations.
GCP_USEKERNING | The font contains a kerning table which can be used to provide better spacing between the characters and glyphs.
GCP_REORDER | The language requires reordering for display—for example, Hebrew or Arabic.

The return value, when masked with FLI_MASK, can be passed directly to the GetCharacterPlacement function.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GetCharacterPlacement


GetFontUnicodeRanges

The GetFontUnicodeRanges function returns information about which Unicode characters are supported by a font. The information is returned as a GLYPHSET structure.

DWORD GetFontUnicodeRanges(
  HDC hdc,         // handle to DC
  LPGLYPHSET lpgs  // glyph set
);

Parameters

hdc
[in] Handle to the device context.
lpgs

[out] Pointer to a GLYPHSET structure that receives the glyph set information. If this parameter is NULL, the function returns the size of the GLYPHSET structure required to store the information.

Return Values

If the function succeeds, it returns number of bytes written to the GLYPHSET structure or, if the lpgs parameter is NULL, it returns the size of the GLYPHSET structure required to store the information.

If the function fails, it returns zero.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GLYPHSET


GetGlyphIndices

The GetGlyphIndices function translates a string into an array of glyph indices. The function can be used to determine whether a glyph exists in a font.

DWORD GetGlyphIndices(
  HDC hdc,       // handle to DC
  LPCTSTR lpstr, // string to convert
  int c,         // number of characters in string
  LPWORD pgi,    // array of glyph indices
  DWORD fl       // glyph options
);

Parameters

hdc
[in] Handle to the device context.
lpstr
[in] Pointer to the string to be converted.
c
[in] Length of the string in pgi. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.
pgi
[out] Array of glyph indices corresponding to the characters in the string.
fl
[in] Specifies how glyphs should be handled if they are not supported. This parameter can be the following value.
Value | Meaning
GGI_MARK_NONEXISTING_GLYPHS | Marks unsupported glyphs with the hexadecimal value 0xffff.

Return Values

If the function succeeds, it returns the number of bytes (for the ANSI function) or WORDs (for the Unicode function) converted.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetFontUnicodeRanges


GetGlyphOutline

The GetGlyphOutline function retrieves the outline or bitmap for a character in the TrueType font that is selected into the specified device context.

DWORD GetGlyphOutline(
  HDC hdc,             // handle to DC
  UINT uChar,          // character to query
  UINT uFormat,        // data format
  LPGLYPHMETRICS lpgm, // glyph metrics
  DWORD cbBuffer,      // size of data buffer
  LPVOID lpvBuffer,    // data buffer
  CONST MAT2 *lpmat2   // transformation matrix
);

Parameters

hdc
[in] Handle to the device context.
uChar
[in] Specifies the character for which data is to be returned.
uFormat
[in] Specifies the format of the data that the function retrieves. This parameter can be one of the following values.
Value | Meaning
GGO_BEZIER | Windows 2000 or later: The function retrieves the curve data as a cubic Bézier spline (not in quadratic spline format).
GGO_BITMAP | The function retrieves the glyph bitmap. For information about memory allocation, see the following Remarks section.
GGO_GLYPH_INDEX | Windows 95, Windows NT 4.0, and Windows 2000 or later: Indicates that the uChar parameter is a TrueType Glyph Index rather than a character code. See the ExtTextOut function for additional remarks on Glyph Indexing.
GGO_GRAY2_BITMAP | Windows 95, Windows NT 4.0, and Windows 2000 or later: The function retrieves a glyph bitmap that contains five levels of gray.
GGO_GRAY4_BITMAP | Windows 95, Windows NT 4.0, and Windows 2000 or later: The function retrieves a glyph bitmap that contains 17 levels of gray.
GGO_GRAY8_BITMAP | Windows 95, Windows NT 4.0, and Windows 2000 or later: The function retrieves a glyph bitmap that contains 65 levels of gray.
GGO_METRICS | The function only retrieves the GLYPHMETRICS structure specified by lpgm. The other buffers are ignored. This value affects the meaning of the function's return value upon failure; see the Return Values section.
GGO_NATIVE | The function retrieves the curve data points in the rasterizer's native format and uses the font's design units.
GGO_UNHINTED | Windows 2000 or later: The function only returns unhinted outlines. This flag only works in conjunction with GGO_BEZIER and GGO_NATIVE.

Note that, for the GGO_GRAYn_BITMAP values, the function retrieves a glyph bitmap that contains n^2+1 (n squared plus one) levels of gray.

lpgm
[out] Pointer to the GLYPHMETRICS structure describing the placement of the glyph in the character cell.
cbBuffer
[in] Specifies the size, in bytes, of the buffer (*lpvBuffer) where the function is to copy information about the outline character. If this value is zero, the function returns the required size of the buffer.
lpvBuffer
[out] Pointer to the buffer that receives information about the outline character. If this value is NULL, the function returns the required size of the buffer.
lpmat2
[in] Pointer to a MAT2 structure specifying a transformation matrix for the character.

Return Values

If GGO_BITMAP, GGO_GRAY2_BITMAP, GGO_GRAY4_BITMAP, GGO_GRAY8_BITMAP, or GGO_NATIVE is specified and the function succeeds, the return value is greater than zero; otherwise, the return value is GDI_ERROR. If one of these flags is specified and the buffer size or address is zero, the return value specifies the required buffer size, in bytes.

If GGO_METRICS is specified and the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The glyph outline returned by the GetGlyphOutline function is for a grid-fitted glyph. (A grid-fitted glyph is a glyph that has been modified so that its bitmapped image conforms as closely as possible to the original design of the glyph.) If an application needs an unmodified glyph outline, it can request the glyph outline for a character in a font whose size is equal to the font's em unit. The value for a font's em unit is stored in the otmEMSquare member of the OUTLINETEXTMETRIC structure.

The glyph bitmap returned by GetGlyphOutline when GGO_BITMAP is specified is a DWORD-aligned, row-oriented, monochrome bitmap. When GGO_GRAY2_BITMAP is specified, the bitmap returned is a DWORD-aligned, row-oriented array of bytes whose values range from 0 to 4. When GGO_GRAY4_BITMAP is specified, the bitmap returned is a DWORD-aligned, row-oriented array of bytes whose values range from 0 to 16. When GGO_GRAY8_BITMAP is specified, the bitmap returned is a DWORD-aligned, row-oriented array of bytes whose values range from 0 to 64.

The native buffer returned by GetGlyphOutline when GGO_NATIVE is specified is a glyph outline. A glyph outline is returned as a series of one or more contours defined by a TTPOLYGONHEADER structure followed by one or more curves. Each curve in the contour is defined by a TTPOLYCURVE structure followed by a number of POINTFX data points. POINTFX points are absolute positions, not relative moves. The starting point of a contour is given by the pfxStart member of the TTPOLYGONHEADER structure. The starting point of each curve is the last point of the previous curve or the starting point of the contour. The count of data points in a curve is stored in the cpfx member of TTPOLYCURVE structure. The size of each contour in the buffer, in bytes, is stored in the cb member of TTPOLYGONHEADER structure. Additional curve definitions are packed into the buffer following preceeding curves and additional contours are packed into the buffer following preceeding contours. The buffer contains as many contours as fit within the buffer returned by GetGlyphOutline.

The GLYPHMETRICS structure specifies the width of the character cell and the location of a glyph within the character cell. The origin of the character cell is located at the left side of the cell at the baseline of the font. The location of the glyph origin is relative to the character cell origin. The height of a character cell, the baseline, and other metrics global to the font are given by the OUTLINETEXTMETRIC structure.

An application can alter the characters retrieved in bitmap or native format by specifying a 2-by-2 transformation matrix in the lpMatrix parameter. For example the glyph can be modified by shear, rotation, scaling, or any combination of the three using matrix multiplication.

Additional information on a glyph outlines is located in the TrueType and the OpenType technical specifications.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, FORM_INFO_1, GetOutlineTextMetrics, GLYPHMETRICS, MAT2, OUTLINETEXTMETRIC, POINT , POINTFX, TTPOLYCURVE, TTPOLYGONHEADER


GetKerningPairs

The GetKerningPairs function retrieves the character-kerning pairs for the currently selected font for the specified device context.

DWORD GetKerningPairs(
  HDC hdc,                 // handle to DC
  DWORD nNumPairs,         // number of kerning pairs
  LPKERNINGPAIR lpkrnpair  // array of kerning pairs
);

Parameters

hdc
[in] Handle to the device context.
nNumPairs
[in] Specifies the number of pairs in the lpkrnpair array. If the font has more than nNumPairs kerning pairs, the function returns an error.
lpkrnpair
[out] Pointer to an array of KERNINGPAIR structures that receives the kerning pairs. The array must contain at least as many structures as specified by the nNumPairs parameter. If this parameter is NULL, the function returns the total number of kerning pairs for the font.

Return Values

If the function succeeds, the return value is the number of kerning pairs returned.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, KERNINGPAIR


GetOutlineTextMetrics

The GetOutlineTextMetrics function retrieves text metrics for TrueType fonts.

UINT GetOutlineTextMetrics(
  HDC hdc,                    // handle to DC
  UINT cbData,                // size of metric data array
  LPOUTLINETEXTMETRIC lpOTM   // metric data array
);

Parameters

hdc
[in] Handle to the device context.
cbData
[in] Specifies the size, in bytes, of the array that receives the text metrics.
lpOTM
[out] Pointer 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.

Return Values

If the function succeeds, the return value is nonzero or the size of the required buffer.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The OUTLINETEXTMETRIC structure contains most of the text metric information provided for TrueType fonts (including a TEXTMETRIC structure). The sizes returned in the OUTLINETEXTMETRIC structures are in logical units; they depend on the current mapping mode.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextMetrics, OUTLINETEXTMETRIC, TEXTMETRIC


GetRasterizerCaps

The GetRasterizerCaps function returns flags indicating whether TrueType fonts are installed in the system.

BOOL GetRasterizerCaps(
  LPRASTERIZER_STATUS lprs,  // rasterizer information
  UINT cb                    // rasterizer information size
);

Parameters

lprs
[out] Pointer to a RASTERIZER_STATUS structure that receives information about the rasterizer.
cb
[in] Specifies the number of bytes to be copied into the structure pointed to by the lprs parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The GetRasterizerCaps function enables applications and printer drivers to determine whether TrueType fonts are installed.

If the TT_AVAILABLE flag is set in the wFlags member of the RASTERIZER_STATUS structure, at least one TrueType font is installed. If the TT_ENABLED flag is set, TrueType is enabled for the system.

The actual number of bytes copied is either the member specified in the cb parameter or the length of the RASTERIZER_STATUS structure, whichever is less.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetOutlineTextMetrics, RASTERIZER_STATUS


GetTabbedTextExtent

The GetTabbedTextExtent function computes the width and height of a character string. If the string contains one or more tab characters, the width of the string is based upon the specified tab stops. The GetTabbedTextExtent function uses the currently selected font to compute the dimensions of the string.

DWORD GetTabbedTextExtent(
  HDC hDC,                        // handle to DC
  LPCTSTR lpString,               // character string
  int nCount,                     // number of characters
  int nTabPositions,              // number of tab positions
  CONST LPINT lpnTabStopPositions // array of tab positions
);

Parameters

hDC
[in] Handle to the device context.
lpString
[in] Pointer to a character string.
nCount
[in] Specifies the length of the text string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

nTabPositions
[in] Specifies the number of tab-stop positions in the array pointed to by the lpnTabStopPositions parameter.
lpnTabStopPositions
[in] Pointer to an array containing the tab-stop positions, in device units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array.

Return Values

If the function succeeds, the return value is the dimensions of the string in logical units. The height is in the high-order word and the width is in the low-order word.

If the function fails, the return value is 0. GetTabbedTextExtent will fail if hDC is invalid and if nTabPositions is less than 0.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

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

Because 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 the nTabPositions parameter is zero and the lpnTabStopPositions parameter 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 array to which lpnTabStopPositions points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextExtentPoint32, HIWORD, LOWORD, TabbedTextOut


GetTextAlign

The GetTextAlign function retrieves the text-alignment setting for the specified device context.

UINT GetTextAlign(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the status of the text-alignment flags. For more information about the return value, see the Remarks section. The return value is a combination of the following values.

Value | Meaning
TA_BASELINE | The reference point is on the base line of the text.
TA_BOTTOM | The reference point is on the bottom edge of the bounding rectangle.
TA_TOP | The reference point is on the top edge of the bounding rectangle.
TA_CENTER | The reference point is aligned horizontally with the center of the bounding rectangle.
TA_LEFT | The reference point is on the left edge of the bounding rectangle.
TA_RIGHT | The reference point is on the right edge of the bounding rectangle.
TA_RTLREADING | Middle-Eastern Windows: The text is laid out in right to left reading order, as opposed to the default left to right order. This only applies when the font selected into the device context is either Hebrew or Arabic.
TA_NOUPDATECP | The current position is not updated after each text output call.
TA_UPDATECP | The current position is updated after each text output call.

When the current font has a vertical default base line (as with Kanji), the following values are used instead of TA_BASELINE and TA_CENTER.

Value | Meaning
VTA_BASELINE | The reference point is on the base line of the text.
VTA_CENTER | The reference point is aligned vertically with the center of the bounding rectangle.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The bounding rectangle is a rectangle bounding all of the character cells in a string of text. Its dimensions can be obtained by calling the GetTextExtentPoint32 function.

The text-alignment flags determine how the TextOut and ExtTextOut functions align a string of text in relation to the string's reference point provided to TextOut or ExtTextOut.

The text-alignment flags are not necessarily single bit flags and may be equal to zero. The flags must be examined in groups of related flags, as shown in the following list.

TA_LEFT, TA_RIGHT, and TA_CENTER
TA_BOTTOM, TA_TOP, and TA_BASELINE
TA_NOUPDATECP and TA_UPDATECP

If the current font has a vertical default base line, the related flags are as shown in the following list.

TA_LEFT, TA_RIGHT, and VTA_BASELINE
TA_BOTTOM, TA_TOP, and VTA_CENTER
TA_NOUPDATECP and TA_UPDATECP

To verify that a particular flag is set in the return value of this function

  1. Apply the bitwise OR operator to the flag and its related flags.
  2. Apply the bitwise AND operator to the result and the return value.
  3. Test for the equality of this result and the flag.

For examples, see Setting the Text Alignment.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GetTextExtentPoint32, SetTextAlign, TextOut


GetTextCharacterExtra

The GetTextCharacterExtra function retrieves the current intercharacter spacing for the specified device context.

int GetTextCharacterExtra(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the current intercharacter spacing.

If the function fails, the return value is 0x8000000.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The intercharacter spacing defines the extra space, in logical units along the base line, that the TextOut or ExtTextOut functions add to each character as a line is written. The spacing is used to expand lines of text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, SetTextCharacterExtra, TextOut


GetTextColor

The GetTextColor function retrieves the current text color for the specified device context.

COLORREF GetTextColor(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is the current text color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Remarks

The text color defines the foreground color of characters drawn by using the TextOut or ExtTextOut function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, SetTextColor, TextOut, COLORREF


GetTextExtentExPoint

The GetTextExtentExPoint function 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. (A text extent is the distance between the beginning of the space and a character that will fit in the space.) This information is useful for word-wrapping calculations.

BOOL GetTextExtentExPoint(
  HDC hdc,         // handle to DC
  LPCTSTR lpszStr, // character string
  int cchString,   // number of characters
  int nMaxExtent,  // maximum width of formatted string
  LPINT lpnFit,    // maximum number of characters
  LPINT alpDx,     // array of partial string widths
  LPSIZE lpSize    // string dimensions
);

Parameters

hdc
[in] Handle to the device context.
lpszStr
[in] Pointer to the null-terminated string for which extents are to be retrieved.
cchString
[in] Specifies the number of characters in the string pointed to by the lpszStr parameter. For an ANSI call it specifies the string length in bytes and for a Unicode it specifies the string length in WORDs. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

nMaxExtent
[in] Specifies the maximum allowable width, in logical units, of the formatted string.
lpnFit
[out] Pointer to an integer that receives a count of the maximum number of characters that will fit in the space specified by the nMaxExtent parameter. When the lpnFit parameter is NULL, the nMaxExtent parameter is ignored.
alpDx
[out] Pointer to an array of integers that receives partial string extents. Each element in the array gives the distance, in logical units, between the beginning of the string and one of the characters that fits in the space specified by the nMaxExtent parameter. This array must have at least as many elements as characters specified by the cchString parameter because the entire array is used internally. The function fills the array with valid extents for as many characters as are specified by the lpnFit parameter. Any values in the rest of the array should be ignored. If alpDx is NULL, the function does not compute partial string widths.

For complex scripts, where a sequence of characters may be represented by any number of glyphs, the values in the alpDx array up to the number specified by the lpnFit parameter match one-to-one with code points. Again, you should ignore the rest of the values in the alpDx array.

lpSize
[out] Pointer to a SIZE structure that receives the dimensions of the string, in logical units. This parameter cannot be NULL.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If both the lpnFit and alpDx parameters are NULL, calling the GetTextExtentExPoint function is equivalent to calling the GetTextExtentPoint function.

For the ANSI version of GetTextExtentExPoint, the lpDx array has the same number of INT values as there are bytes in lpString. The INT values that correspond to the two bytes of a DBCS character are each the extent of the entire composite character.

Note, the alpDx values for GetTextExtentExPoint are not the same as the lpDx values for ExtTextOut. To use the alpDx values in lpDx, you must first process them.

When returning the text extent, this function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both the horizontal and vertical measurements of the text. Even if using a font specifying a nonzero escapement, this function will not use the angle while computing the text extent—the application must convert it explicitly.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextExtentPoint, SIZE


GetTextExtentExPointI

The GetTextExtentExPointI function 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. (A text extent is the distance between the beginning of the space and a character that will fit in the space.) This information is useful for word-wrapping calculations.

BOOL GetTextExtentExPointI(
  HDC hdc,         // handle to DC
  LPWORD pgiIn,    // array of glyph indices
  int cgi,         // number of glyphs in array
  int nMaxExtent,  // maximum width of formatted string
  LPINT lpnFit,    // maximum number of characters
  LPINT alpDx,     // array of partial string widths
  LPSIZE lpSize    // string dimensions
);

Parameters

hdc
[in] Handle to the device context.
pgiIn
[in] Pointer to an array of glyph indices for which extents are to be retrieved.
cgi
[in] Specifies the number of glyphs in the array pointed to by the pgiIn parameter.
nMaxExtent
[in] Specifies the maximum allowable width, in logical units, of the formatted string.
lpnFit
[out] Pointer to an integer that receives a count of the maximum number of characters that will fit in the space specified by the nMaxExtent parameter. When the lpnFit parameter is NULL, the nMaxExtent parameter is ignored.
alpDx
[out] 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 the nMaxExtent parameter. Although this array should have at least as many elements as glyph indices specified by the cgi parameter, the function fills the array with extents only for as many glyph indices as are specified by the lpnFit parameter. If lpnDx is NULL, the function does not compute partial string widths.
lpSize
[out] Pointer to a SIZE structure that receives the dimensions of the glyph indices array, in logical units. This value cannot be NULL.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

If both the lpnFit and lpnDx parameters are NULL, calling the GetTextExtentExPointI function is equivalent to calling the GetTextExtentPointI function.

When returning the text extent, this function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both the horizontal and vertical measurements of the text. Even if using a font specifying a nonzero escapement, this function will not use the angle while computing the text extent—the application must convert it explicitly.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextExtentPoint, SIZE


GetTextExtentPoint

The GetTextExtentPoint function computes the width and height of the specified string of text.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should call the GetTextExtentPoint32 function, which provides more accurate results.

BOOL GetTextExtentPoint(
  HDC hdc,           // handle to DC
  LPCTSTR lpString,  // text string
  int cbString,      // number of characters in string
  LPSIZE lpSize      // string size
);

Parameters

hdc
[in] Handle to the device context.
lpString
[in] Pointer to the string that specifies the text. The string does not need to be zero-terminated, since cbString specifies the length of the string.
cbString
[in] Specifies the length of the string pointed to by lpString. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note, for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) take one WORD while Unicode surrogates take two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

lpSize
[out] Pointer to a SIZE structure that receives the dimensions of the string.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

The GetTextExtentPoint function uses the currently selected font to compute the dimensions of the string. The width and height, in logical units, are computed without considering any clipping. Also, this function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both the horizontal and vertical measurements of the text. Even if using a font specifying a nonzero escapement, this function will not use the angle while computing the text extent—the application must convert it explicitly.

Because some devices kern characters, the sum of the extents of the characters in a string may not be equal to the extent of the string.

The calculated string width takes into account the intercharacter spacing set by the SetTextCharacterExtra function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextExtentPoint32, SetTextCharacterExtra, SIZE


GetTextExtentPoint32

The GetTextExtentPoint32 function computes the width and height of the specified string of text.

BOOL GetTextExtentPoint32(
  HDC hdc,           // handle to DC
  LPCTSTR lpString,  // text string
  int cbString,      // characters in string
  LPSIZE lpSize      // string size
);

Parameters

hdc
[in] Handle to the device context.
lpString
[in] Pointer to a buffer that specifies the text string. The string does not need to be zero-terminated, because the cbString parameter specifies the length of the string.
cbString
[in] Specifies the length of the lpString buffer. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

lpSize
[out] Pointer to a SIZE structure that receives the dimensions of the string.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The GetTextExtentPoint32 function uses the currently selected font to compute the dimensions of the string. The width and height, in logical units, are computed without considering any clipping.

Because some devices kern characters, the sum of the extents of the characters in a string may not be equal to the extent of the string.

The calculated string width takes into account the intercharacter spacing set by the SetTextCharacterExtra function.

When returning the text extent, this function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both the horizontal and vertical measurements of the text. Even if using a font specifying a nonzero escapement, this function will not use the angle while computing the text extent—the application must convert it explicitly.

For examples, see Drawing Text from Different Fonts on the Same Line.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Fonts and Text Overview, Font and Text Functions, SetTextCharacterExtra, SIZE


GetTextExtentPointI

The GetTextExtentPointI function computes the width and height of the specified array of glyph indices.

BOOL GetTextExtentPointI(
  HDC hdc,           // handle to DC
  LPWORD pgiIn,      // glyph indices
  int cgi,           // number of indices in array
  LPSIZE lpSize      // string size
);

Parameters

hdc
[in] Handle to the device context.
pgiIn
[in] Pointer to array of glyph indices.
cgi
[in] Specifies the number of glyph indices.
lpSize
[out] Pointer to a SIZE structure that receives the dimensions of the string.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

The GetTextExtentPointI function uses the currently selected font to compute the dimensions of the array of glyph indices. The width and height, in logical units, are computed without considering any clipping.

When returning the text extent, this function assumes that the text is horizontal, that is, that the escapement is always 0. This is true for both the horizontal and vertical measurements of the text. Even if using a font specifying a nonzero escapement, this function will not use the angle while computing the text extent - the application must convert it explicitly.

Because some devices kern characters, the sum of the extents of the individual glyph indices may not be equal to the extent of the entire array of glyph indices.

The calculated string width takes into account the intercharacter spacing set by the SetTextCharacterExtra function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextExtentPoint, GetTextExtentPoint32, SetTextCharacterExtra, SIZE


GetTextFace

The GetTextFace function retrieves the typeface name of the font that is selected into the specified device context.

int GetTextFace(
  HDC hdc,            // handle to DC
  int nCount,         // length of typeface name buffer
  LPTSTR lpFaceName   // typeface name buffer
);

Parameters

hdc
[in] Handle to the device context.
nCount
[in] Specifies the length of the buffer pointed to by lpFaceName. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.
lpFaceName
[out] Pointer to the buffer that receives the typeface name. If this parameter is NULL, the function returns the number of characters in the name, including the terminating null character.

Return Values

If the function succeeds, the return value is the number of characters copied to the buffer.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

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

If the name is longer than the number of characters specified by the nCount parameter, the name is truncated.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextAlign, GetTextColor, GetTextExtentPoint32, GetTextMetrics


GetTextMetrics

The GetTextMetrics function fills the specified buffer with the metrics for the currently selected font.

BOOL GetTextMetrics(
  HDC hdc,            // handle to DC
  LPTEXTMETRIC lptm   // text metrics
);

Parameters

hdc
[in] Handle to the device context.
lptm
[out] Pointer to the TEXTMETRIC structure that receives the text metrics.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For examples, see Displaying Keyboard Input, Drawing Text from Different Fonts on the Same Line.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextAlign, GetTextExtentPoint32, GetTextFace, SetTextJustification, TEXTMETRIC


PolyTextOut

The PolyTextOut function draws several strings using the font and text colors currently selected in the specified device context.

BOOL PolyTextOut(
  HDC hdc,                // handle to DC
  CONST POLYTEXT *pptxt,  // array of strings
  int cStrings            // number of strings in array
);

Parameters

hdc
[in] Handle to the device context.
pptxt
[in] Pointer to an array of POLYTEXT structures describing the strings to be drawn. The array contains one structure for each string to be drawn.
cStrings
[in] Specifies the number of POLYTEXT structures in the pptxt array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Each POLYTEXT structure contains the coordinates of a reference point that Windows uses to align the corresponding string of text. An application can specify how the reference point is used by calling the SetTextAlign function. An application can determine the current text-alignment setting for the specified device context by calling the GetTextAlign function.

To draw a single string of text, the application should call the ExtTextOut function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GetTextAlign, POLYTEXT, SetTextAlign


RemoveFontMemResourceEx

The RemoveFontMemResourceEx function removes the fonts added from a memory image file.

BOOL RemoveFontMemResourceEx(
  HANDLE fh   // handle to the font resource
);

Parameters

fh
[in] Handle to the font-resource. This handle is returned by the AddFontMemResourceEx function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

This function removes a font that was added by the AddFontMemResourceEx function. To remove the font, specify the same path and flags as were used in AddFontMemResourceEx. This function will only remove the font that is specified by fh.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, AddFontMemResourceEx, SendMessage


RemoveFontResource

The RemoveFontResource function removes the fonts in the specified file from the system font table.

If the font was added using the AddFontResourceEx function, you must use the RemoveFontResourceEx function.

BOOL RemoveFontResource(
  LPCTSTR lpFileName   // name of font file
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that names a font resource file.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application that adds or removes fonts from the system font table should notify other windows of the change by sending a WM_FONTCHANGE message to all top-level windows in the system. The application sends this message by calling the SendMessage function with the hwnd parameter set to HWND_BROADCAST.

If there are outstanding references to a font, the associated resource remains loaded until no device context is using it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, AddFontResource, RemoveFontResourceEx, SendMessage


RemoveFontResourceEx

The RemoveFontResourceEx function removes the fonts in the specified file from the system font table.

BOOL RemoveFontResourceEx(
  LPCTSTR lpFileName,  // name of font file
  DWORD fl,            // font characteristics
  PVOID pdv            // Reserved.
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that names a font resource file.
fl
[in] Specifies characteristics of the font to be removed from the system. In order for the font to be removed, the flags used must be the same as when the font was added with the AddFontResourceEx function. See the AddFontResourceEx function for more information.
pdv
[in] Reserved. It must be 0.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

This function will only remove the font if the flags specified are the same as when then font was added with the AddFontResourceEx function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Fonts and Text Overview, Font and Text Functions, AddFontResourceEx, SendMessage


SetMapperFlags

The SetMapperFlags function alters the algorithm the font mapper uses when it maps logical fonts to physical fonts.

DWORD SetMapperFlags(
  HDC hdc,       // handle to DC
  DWORD dwFlag   // font-mapper option
);

Parameters

hdc
[in] Handle to the device context that contains the font-mapper flag.
dwFlag
[in] Specifies whether the font mapper should attempt to match a font's aspect ratio to the current device's aspect ratio. If bit zero is set, the mapper selects only matching fonts.

Return Values

If the function succeeds, the return value is the previous value of the font-mapper flag.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If the dwFlag parameter is set and no matching fonts exist, Windows chooses a new aspect ratio and retrieves a font that matches this ratio.

The remaining bits of the dwFlag parameter must be zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, GetAspectRatioFilterEx


SetTextAlign

The SetTextAlign function sets the text-alignment flags for the specified device context.

UINT SetTextAlign(
  HDC hdc,     // handle to DC
  UINT fMode   // text-alignment option
);

Parameters

hdc
[in] Handle to the device context.
fMode
[in] Specifies the text alignment by using a mask of the values in the following list. Only one flag can be chosen from those that affect horizontal and vertical alignment. In addition, only one of the two flags that alter the current position can be chosen.
Value | Meaning
TA_BASELINE | The reference point will be on the base line of the text.
TA_BOTTOM | The reference point will be on the bottom edge of the bounding rectangle.
TA_TOP | The reference point will be on the top edge of the bounding rectangle.
TA_CENTER | The reference point will be aligned horizontally with the center of the bounding rectangle.
TA_LEFT | The reference point will be on the left edge of the bounding rectangle.
TA_RIGHT | The reference point will be on the right edge of the bounding rectangle.
TA_NOUPDATECP | The current position is not updated after each text output call. The reference point is passed to the text output function.
TA_RTLREADING | Middle-Eastern Windows: The text is laid out in right to left reading order, as opposed to the default left to right order. This applies only when the font selected into the device context is either Hebrew or Arabic.
TA_UPDATECP | The current position is updated after each text output call. The current position is used as the reference point.

When the current font has a vertical default base line, as with Kanji, the following values must be used instead of TA_BASELINE and TA_CENTER.
Value | Meaning
VTA_BASELINE | The reference point will be on the base line of the text.
VTA_CENTER | The reference point will be aligned vertically with the center of the bounding rectangle.

The default values are TA_LEFT, TA_TOP, and TA_NOUPDATECP.

Return Values

If the function succeeds, the return value is the previous text-alignment setting.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The TextOut and ExtTextOut functions use the text-alignment flags to position a string of text on a display or other device. The flags specify the relationship between a reference point and a rectangle that bounds the text. The reference point is either the current position or a point passed to a text output function.

The rectangle that bounds the text is formed by the character cells in the text string.

The best way to get left-aligned text is to use either

SetTextAlign (hdc, GetTextAlign(hdc) & (~TA_CENTER))

– or –

SetTextAlign (hdc,TA_LEFT | <other flags>)

You can also use SetTextAlign (hdc, TA_LEFT) for this purpose, but this loses any vertical or right-to-left settings.

Note You should not use SetTextAlign with TA_UPDATECP when you are using ScriptStringOut, because selected text is not rendered correctly. If you must use this flag, you can unset and reset it as necessary to avoid the problem.

For an example, see Setting the Text Alignment.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GetTextAlign, ScriptStringOut, TextOut


SetTextCharacterExtra

The SetTextCharacterExtra function sets the intercharacter spacing. Intercharacter spacing is added to each character, including break characters, when the system writes a line of text.

int SetTextCharacterExtra(
  HDC hdc,         // handle to DC
  int nCharExtra   // extra-space value
);

Parameters

hdc
[in] Handle to the device context.
nCharExtra
[in] Specifies the amount of extra space, in logical units, to be added to each character. If the current mapping mode is not MM_TEXT, the nCharExtra parameter is transformed and rounded to the nearest pixel.

Return Values

If the function succeeds, the return value is the previous intercharacter spacing.

If the function fails, the return value is 0x80000000.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, DrawText, GetTextCharacterExtra, TextOut


SetTextColor

The SetTextColor function sets the text color for the specified device context to the specified color.

COLORREF SetTextColor(
  HDC hdc,           // handle to DC
  COLORREF crColor   // text color
);

Parameters

hdc
[in] Handle to the device context.
crColor
[in] Specifies the color of the text.

Return Values

If the function succeeds, the return value is a color reference for the previous text color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The text color is used to draw the face of each character written by the TextOut and ExtTextOut functions. The text color is also used in converting bitmaps from color to monochrome and vice versa.

For an example, see Setting Fonts for Menu-Item Text Strings.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, BitBlt, ExtTextOut, GetTextColor, RGB, SetBkColor, StretchBlt, TextOut, COLORREF


SetTextJustification

The SetTextJustification function specifies the amount of space the system should add to the break characters in a string of text. The space is added when an application calls the TextOut or ExtTextOut functions.

BOOL SetTextJustification(
  HDC hdc,          // handle to DC
  int nBreakExtra,  // length of extra space
  int nBreakCount   // count of space characters
);

Parameters

hdc
[in] Handle to the device context.
nBreakExtra
[in] Specifies the total extra space, in logical units, to be added to the line of text. If the current mapping mode is not MM_TEXT, the value identified by the nBreakExtra parameter is transformed and rounded to the nearest pixel.
nBreakCount
[in] Specifies the number of break characters in the line.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The break character is usually the space character (ASCII 32), but it may be defined by a font as some other character. The GetTextMetrics function can be used to retrieve a font's break character.

The TextOut function distributes the specified extra space evenly among the break characters in the line.

The GetTextExtentPoint32 function is always used with the SetTextJustification function. The GetTextExtentPoint32 function computes the width of a specified line before justification. This width must be known before an appropriate nBreakExtra value can be computed.

SetTextJustification can be used to justify a line that contains multiple strings in different fonts. In this case, each string must be justified separately.

Because rounding errors can occur during justification, the system keeps a running error term that defines the current error value. When justifying a line that contains multiple runs, GetTextExtentPoint automatically uses this error term when it computes the extent of the next run, allowing TextOut to blend the error into the new run. After each line has been justified, 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 zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Fonts and Text Overview, Font and Text Functions, ExtTextOut, GetTextExtentPoint32, GetTextMetrics, TextOut


TabbedTextOut

The TabbedTextOut function writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions. Text is written in the currently selected font, background color, and text color.

LONG TabbedTextOut(
  HDC hDC,                         // handle to DC
  int X,                           // x-coord of start
  int Y,                           // y-coord of start
  LPCTSTR lpString,                // character string
  int nCount,                      // number of characters
  int nTabPositions,               // number of tabs in array
  CONST LPINT lpnTabStopPositions, // array of tab positions
  int nTabOrigin                   // start of tab expansion
);

Parameters

hDC
[in] Handle to the device context.
X
[in] Specifies the x-coordinate of the starting point of the string, in logical units.
Y
[in] Specifies the y-coordinate of the starting point of the string, in logical units.
lpString
[in] Pointer to the character string to draw. The string does not need to be zero-terminated, since nCount specifies the length of the string.
nCount
[in] Specifies the length of the string pointed to by lpString. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each, while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

nTabPositions
[in] Specifies the number of values in the array of tab-stop positions.
lpnTabStopPositions
[in] Pointer 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.

Windows 95: A tab stop can be specified as a negative value, which causes text to be right-aligned on the tab stop rather than left-aligned.

nTabOrigin
[in] Specifies the x-coordinate of the starting position from which tabs are expanded, in logical units.

Return Values

If the function succeeds, the return value is the dimensions, in logical units, of the string. The height is in the high-order word and the width is in the low-order word.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If the nTabPositions parameter is zero and the lpnTabStopPositions parameter 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 TabbedTextOut 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 TabbedTextOut function. If an application needs to update the current position when it calls TabbedTextOut, the application can call the SetTextAlign function with the wFlags parameter set to TA_UPDATECP. When this flag is set, the system ignores the X and Y parameters on subsequent calls to the TabbedTextOut function, using the current position instead.

For an example, see Getting Hardware Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Fonts and Text Overview, Font and Text Functions, DrawText, GetTabbedTextExtent, GrayString, SelectObject, SetBkColor, SetTextAlign, SetTextColor, TextOut


TextOut

The TextOut function writes a character string at the specified location, using the currently selected font, background color, and text color.

BOOL TextOut(
  HDC hdc,           // handle to DC
  int nXStart,       // x-coordinate of starting position
  int nYStart,       // y-coordinate of starting position
  LPCTSTR lpString,  // character string
  int cbString       // number of characters
);

Parameters

hdc
[in] Handle to the device context.
nXStart
[in] Specifies the logical x-coordinate of the reference point that the system uses to align the string.
nYStart
[in] Specifies the logical y-coordinate of the reference point that the system uses to align the string.
lpString
[in] Pointer to the string to be drawn. The string does not need to be zero-terminated, since cbString specifies the length of the string.
cbString
[in] Specifies the length of the string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.

Windows 95/98/Me: This value may not exceed 8192.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Although not true in general, Windows 95/98 supports the Unicode version of this function as well as the ANSI version.

The interpretation of the reference point depends on the current text-alignment mode. An application can retrieve this mode by calling the GetTextAlign function; an application can alter this mode by calling the SetTextAlign function.

By default, the current position is not used or updated by this function. However, an application can call the SetTextAlign function with the fMode parameter set to TA_UPDATECP to permit the system to use and update the current position each time the application calls TextOut for a specified device context. When this flag is set, the system ignores the nXStart and nYStart parameters on subsequent TextOut calls.

When the TextOut function is placed inside a path bracket, the system generates a path for the TrueType text that includes each character plus its character box. The region generated is the character box minus the text, rather than the text itself. You can obtain the region enclosed by the outline of the TrueType text by setting the background mode to transparent before placing the TextOut function in the path bracket. Following is sample code that demonstrates this procedure.

// Obtain the window's client rectangle
GetClientRect(hwnd, &r);

// THE FIX: by setting the background mode
// to transparent, the region is the text itself
// SetBkMode(hdc, TRANSPARENT);

// Bracket begin a path
BeginPath(hdc);

// Send some text out into the world
TextOut(hdc, r.left, r.top, "Defenestration can be hazardous", 4);

// Bracket end a path
EndPath(hdc);

// Derive a region from that path
SelectClipPath(hdc, RGN_AND);

// This generates the same result as SelectClipPath()
// SelectClipRgn(hdc, PathToRegion(hdc));

// Fill the region with grayness
FillRect(hdc, &r, GetStockObject(GRAY_BRUSH));

For examples, see Enumerating the Installed Fonts.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on all platforms.

See Also

Fonts and Text Overview, Font and Text Functions, GetTextAlign, SelectObject, SetBkColor, SetTextAlign, SetTextColor, TabbedTextOut


Font and Text Structures

The following structures are used with fonts and text.

ABC
ABCFLOAT
AXESLIST
AXISINFO
DESIGNVECTOR
DRAWTEXTPARAMS
ENUMLOGFONT
ENUMLOGFONTEX
ENUMLOGFONTEXDV
ENUMTEXTMETRIC
EXTLOGFONT
FIXED
GCP_RESULTS
GLYPHMETRICS
GLYPHSET
KERNINGPAIR
LOGFONT
MAT2
NEWTEXTMETRIC
NEWTEXTMETRICEX
OUTLINETEXTMETRIC
PANOSE
POINTFX
POLYTEXT
RASTERIZER_STATUS
SIZE
TEXTMETRIC
TTPOLYCURVE
TTPOLYGONHEADER
WCRANGE


ABC

The ABC structure contains the width of a character in a TrueType font.

typedef struct _ABC {
  int     abcA;
  UINT    abcB;
  int     abcC;
} ABC, *PABC;

Members

abcA
Specifies the A spacing of the character. The A spacing is the distance to add to the current position before drawing the character glyph.
abcB
Specifies the B spacing of the character. The B spacing is the width of the drawn portion of the character glyph.
abcC
Specifies the C spacing of the character. The C spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Remarks

The total width of a character is the summation of the A, B, and C spaces. Either the A or the C space can be negative to indicate underhangs or overhangs.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetCharABCWidths


ABCFLOAT

The ABCFLOAT structure contains the A, B, and C widths of a font character.

typedef struct _ABCFLOAT {
  FLOAT   abcfA;
  FLOAT   abcfB;
  FLOAT   abcfC;
} ABCFLOAT, *PABCFLOAT;

Members

abcfA
Specifies the A spacing of the character. The A spacing is the distance to add to the current position before drawing the character glyph.
abcfB
Specifies the B spacing of the character. The B spacing is the width of the drawn portion of the character glyph.
abcfC
Specifies the C spacing of the character. The C spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Remarks

The A, B, and C widths are measured along the base line of the font.

The character increment (total width) of a character is the sum of the A, B, and C spaces. Either the A or the C space can be negative to indicate underhangs or overhangs.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetCharABCWidthsFloat


AXESLIST

The AXESLIST structure contains information on all the axes of a multiple master font.

typedef struct tagAXESLIST {
  DWORD    axlReserved;
  DWORD    axlNumAxes;
  AXISINFO axlAxisInfo[MM_MAX_NUMAXES];
} AXESLIST, *PAXESLIST;

Members

axlReserved
Reserved. Must be STAMP_AXESLIST.
axlNumAxes
Number of axes for a specified multiple master font.
axlAxisInfo
An array of AXISINFO structures. Each AXISINFO structure contains information on an axis of a specified multiple master font. This corresponds to the dvValues array in the DESIGNVECTOR structure.

Remarks

The PostScript Open Type Font does not support multiple master functionality.

The information on the axes of a multiple master font are specified by the AXISINFO structures. The axlNumAxes member specifies the actual size of axlAxisInfo, while MM_MAX_NUMAXES, which equals 16, is the maximum allowed size of axlAxisInfo.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, AXISINFO, DESIGNVECTOR, ENUMTEXTMETRIC


AXISINFO

The AXISINFO structure contains information about an axis of a multiple master font.

typedef struct tagAXISINFO {
  LONG axMinValue;
  LONG axMaxValue;
  TCHAR axAxisName[MM_MAX_AXES_NAMELEN];
} AXISINFO, *PAXISINFO;

Members

axMinValue
Minimum value for this axis.
axMaxValue
Maximum value for this axis.
axAxisName
Name of the axis, specified as an array of characters.

Remarks

The AXISINFO structure contains the name of an axis in a multiple master font and also the minimum and maximum possible values for the axis. The length of the name is MM_MAX_AXES_NAMELEN, which equals 16. An application queries these values before setting its desired values in the DESIGNVECTOR array.

The PostScript Open Type Font does not support multiple master functionality.

For the ANSI version of this structure, axAxisName must be an array of bytes.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, AXESLIST, DESIGNVECTOR


DESIGNVECTOR

The DESIGNVECTOR structure is used by an application to specify values for the axes of a multiple master font.

typedef struct tagDESIGNVECTOR {
  DWORD dvReserved;
  DWORD dvNumAxes;
  LONG dvValues[MM_MAX_NUMAXES];
} DESIGNVECTOR, *PDESIGNVECTOR;

Members

dvReserved
Reserved. Must be STAMP_DESIGNVECTOR.
dvNumAxes
Number of values in the dvValues array.
dvValues
An array specifying the values of the axes of a multiple master OpenType font. This array corresponds to the axlAxisInfo array in the AXESLIST structure.

Remarks

The dvNumAxes member determines the actual size of dvValues, and thus, of DESIGNVECTOR. The constant MM_MAX_NUMAXES, which is 16, specifies the maximum allowed size of the dvValues array.

The PostScript Open Type Font does not support multiple master functionality.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, AddFontResourceEx, AddFontMemResourceEx, RemoveFontResourceEx , AXESLIST


DRAWTEXTPARAMS

The DRAWTEXTPARAMS structure contains extended formatting options for the DrawTextEx function.

typedef struct {
  UINT cbSize;
  int  iTabLength;
  int  iLeftMargin;
  int  iRightMargin;
  UINT uiLengthDrawn;
} DRAWTEXTPARAMS, *LPDRAWTEXTPARAMS;

Members

cbSize
Specifies the structure size, in bytes.
iTabLength
Specifies the size of each tab stop, in units equal to the average character width.
iLeftMargin
Specifies the left margin, in units equal to the average character width.
iRightMargin
Specifies the right margin, in units equal to the average character width.
uiLengthDrawn
Receives the number of characters processed by DrawTextEx, including white-space characters. The number can be the length of the string or the index of the first line that falls below the drawing area. Note that DrawTextEx always processes the entire string if the DT_NOCLIP formatting flag is specified.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, DrawTextEx


ENUMLOGFONT

The ENUMLOGFONT structure defines the attributes of a font, the complete name of a font, and the style of a font.

typedef struct tagENUMLOGFONT {
  LOGFONT elfLogFont;
  TCHAR   elfFullName[LF_FULLFACESIZE];
  TCHAR   elfStyle[LF_FACESIZE];
} ENUMLOGFONT, *LPENUMLOGFONT;

Members

elfLogFont
Specifies a LOGFONT structure that defines the attributes of a font.
elfFullName
Specifies a unique name for the font. For example, ABCD Font Company TrueType Bold Italic Sans Serif.
elfStyle
Specifies the style of the font. For example, Bold Italic.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, EnumFontFamProc, LOGFONT


ENUMLOGFONTEX

The ENUMLOGFONTEX structure contains information about an enumerated font.

typedef struct tagENUMLOGFONTEX {
  LOGFONT  elfLogFont;
  TCHAR  elfFullName[LF_FULLFACESIZE];
  TCHAR  elfStyle[LF_FACESIZE];
  TCHAR  elfScript[LF_FACESIZE];
} ENUMLOGFONTEX, *LPENUMLOGFONTEX;

Members

elfLogFont
Specifies a LOGFONT structure that contains values defining the font attributes.

Windows 95/98/Me: If not a TrueType font, the lfFaceName member of LOGFONT is filled with the unique name of the font.

elfFullName
Specifies a null-terminated string specifying the unique name of the font. For example, ABC Font Company TrueType Bold Italic Sans Serif.

Windows 95/98/Me: Specifies the unique name of a TrueType font. For other type fonts, see explanation in elfLogFont.

elfStyle
Specifies a null-terminated string specifying the style of the font. For example, Bold Italic.
elfScript
Specifies a null-terminated string specifying the script, that is, the character set, of the font. For example, Cyrillic.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, EnumFontFamExProc, EnumFontFamiliesEx, LOGFONT


ENUMLOGFONTEXDV

The ENUMLOGFONTEXDV structure contains the information used to create a font.

typedef struct tagENUMLOGFONTEXDV {
  ENUMLOGFONTEX elfEnumLogfontEx;
  DESIGNVECTOR elfDesignVector;
} ENUMLOGFONTEXDV, *PENUMLOGFONTEXDV

Members

elfEnumLogfontEx
An ENUMLOGFONTEX structure that contains information about the logical attributes of the font.
elfDesignVector
A DESIGNVECTOR structure. This is zero-filled unless the font described is a multiple master OpenType font.

Remarks

The actual size of ENUMLOGFONTEXDV depends on that of DESIGNVECTOR, which, in turn depends on its dvNumAxes member.

Windows 2000 or later: The EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx functions have been modified to return pointers to ENUMTEXTMETRIC and ENUMLOGFONTEXDV to the callback function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, CreateFontIndirectEx, EnumFonts, EnumFontFamilies, EnumFontFamiliesEx, DESIGNVECTOR, ENUMTEXTMETRIC


ENUMTEXTMETRIC

The ENUMTEXTMETRIC structure contains information about a physical font.

typedef struct tagENUMTEXTMETRIC {
  NEWTEXTMETRICEX etmNewTextMetricEx;
  AXESLIST etmAxesList;
} ENUMTEXTMETRIC, *PENUMTEXTMETRIC;

Members

etmNewTextMetricEx
Name of a NEWTEXTMETRICEX structure, containing information about a physical font.
etmAxesList
Name of an AXESLIST structure, containing information about the axes for the font. This is only used for multiple master fonts.

Remarks

ENUMTEXTMETRIC is an extension of NEWTEXTMETRICEX that includes the axis information for a multiple master font.

Windows 2000 or later:The EnumFonts, EnumFontFamilies, and EnumFontFamiliesEx functions have been modified to return pointers to the ENUMTEXTMETRIC and ENUMLOGFONTEXDV structures.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, EnumFontFamilies, EnumFontFamiliesEx, EnumFonts, AXESLIST, ENUMLOGFONTEX, ENUMLOGFONTEXDV, ENUMTEXTMETRIC , NEWTEXTMETRICEX


EXTLOGFONT

The EXTLOGFONT structure defines the attributes of a font.

typedef struct tagEXTLOGFONT {
  LOGFONT elfLogFont;
  TCHAR   elfFullName[LF_FULLFACESIZE];
  TCHAR   elfStyle[LF_FACESIZE];
  DWORD   elfVersion;
  DWORD   elfStyleSize;
  DWORD   elfMatch;
  DWORD   elfReserved;
  BYTE    elfVendorId[ELF_VENDOR_SIZE];
  DWORD   elfCulture;
  PANOSE  elfPanose;
} EXTLOGFONT, *PEXTLOGFONT;

Members

elfLogFont
Specifies some of the attributes of the specified font. This member is a LOGFONT structure.
elfFullName
Specifies a unique name for the font (for example, ABCD Font Company TrueType Bold Italic Sans Serif).
elfStyle
Specifies the style of the font (for example, Bold Italic).
elfVersion
Reserved. Must be zero.
elfStyleSize
This member only has meaning for hinted fonts. It specifies the point size at which the font is hinted. If set to zero, which is its default value, the font is hinted at the point size corresponding to the lfHeight member of the LOGFONT structure specified by elfLogFont.
elfMatch
A unique identifier for an enumerated font. This will be filled in by the graphics device interface (GDI) upon font enumeration.
elfReserved
Reserved; must be zero.
elfVendorId
A 4-byte identifier of the font vendor.
elfCulture
Reserved; must be zero.
elfPanose
A PANOSE structure that specifies the shape of the font. If all members of this structure are set to zero, the elfPanose member is ignored by the font mapper.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, LOGFONT, PANOSE


FIXED

The FIXED structure contains the integral and fractional parts of a fixed-point real number.

typedef struct _FIXED {
  WORD  fract;
  short value;
} FIXED;

Members

fract
Specifies the fractional part of the number.
value
Specifies the integer part of the number.

Remarks

The FIXED structure is used to describe the elements of the MAT2 structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, MAT2


GCP_RESULTS

The GCP_RESULTS structure contains information about characters in a string. This structure receives the results of the GetCharacterPlacement function. For some languages, the first element in the arrays may contain more, language-dependent information.

typedef struct tagGCP_RESULTS {
  DWORD  lStructSize;
  LPTSTR  lpOutString;
  UINT  *lpOrder;
  int  *lpDx;
  int  *lpCaretPos;
  LPSTR lpClass;
  LPWSTR  *lpGlyphs;
  UINT  nGlyphs;
  int  nMaxFit;
} GCP_RESULTS, *LPGCP_RESULTS;

Members

lStructSize
Specifies the size, in bytes, of the structure.
lpOutString
Pointer to the buffer that receives the output string or is NULL if the output string is not needed. The output string is a version of the original string that is in the order that will be displayed on a specified device. Typically the output string is identical to the original string, but may be different if the string needs reordering and the GCP_REORDER flag is set or if the the original string exceeds the maximum extent and the GCP_MAXEXTENT flag is set.
lpOrder
Pointer to the array that receives the ordering indices for the characters in the output string or is NULL if the ordering indices are not needed. The original string needs reordering if the GetFontLanguageInfo function returns the GCP_REORDER value. This is typically used when GetFontLanguageInfo returns the GCP_REORDER flag. For example, in Hebrew, in which the text runs from right to left, the lpOrder array gives the exact locations of each element in the original string.
lpDx
Pointer to the array that receives the distances between adjacent character cells or is NULL if these distances are not needed. If glyph rendering is done, the distances are for the glyphs not the characters, so the resulting array can be used with the ExtTextOut function.

The distances in this array are in display order. To find the distance for the ith character in the original string, use the lpOrder array as follows:

width = lpDx[lpOrder[i]];
lpCaretPos
Pointer to the array that receives the caret position values or is NULL if caret positions are not needed. Each value specifies the caret position immediately before the corresponding character. In some languages the position of the caret for each character may not be immediately to the left of the character. For example, in Hebrew, in which the text runs from right to left, the caret position is to the right of the character. If glyph ordering is done, lpCaretPos matches the original string not the output string. This means that some adjacent values may be the same.

The values in this array are in input order. To find the caret position value for the ith character in the original string, use the array as follows:

position = lpCaretPos[i];
lpClass
Pointer to the array that contains and/or receives character classifications. The values indicate how to lay out characters in the string and are similar (but not identical) to the CT_CTYPE2 values returned by the GetStringTypeEx function. Each element of the array can be set to zero or one of the following values.
Value | Meaning
GCPCLASS_ARABIC | Arabic character.
GCPCLASS_HEBREW | Hebrew character.
GCPCLASS_LATIN | Character from a Latin or other single-byte character set for a left-to-right language.
GCPCLASS_LATINNUMBER | Digit from a Latin or other single-byte character set for a left-to-right language.
GCPCLASS_LOCALNUMBER | Digit from the character set associated with the current font.

In addition, the following can be used when supplying values in the lpClass array with the GCP_CLASSIN flag.
Value | Meaning
GCPCLASS_LATINNUMERICSEPARATOR | Input only. Character used to separate Latin digits, such as acomma or decimal point.
GCPCLASS_LATINNUMERICTERMINATOR | Input only. Character used to terminate Latin digits, such as a plus or minus sign.
GCPCLASS_NEUTRAL | Input only. Character has no specific classification.
GCPCLASS_NUMERICSEPARATOR | Input only. Character used to separate digits, such as a comma or decimal point.

For languages that use the GCP_REORDER flag, the following values can also be used with the GCP_CLASSIN flag. Unlike the preceding values, which can be used anywhere in the lpClass array, all of the following values are used only in the first location in the array. All combine with other classifications.

Note that GCPCLASS_PREBOUNDLTR and GCPCLASS_PREBOUNDRTL are mutually exclusive, as are GCPCLASSPOSTBOUNDLTR and GCPCLASSPOSTBOUNDRTL.
Value | Meaning
GCPCLASS_PREBOUNDLTR | Set lpClass[0] to GCP_CLASS_PREBOUNDLTR to bind the string to left-to-right reading order before the string.
GCPCLASS_PREBOUNDRTL | Set lpClass[0] to GCP_CLASS_PREBOUNDRTL to bind the string to right-to-left reading order before the string.
GCPCLASS_POSTBOUNDLTR | Set lpClass[0] to GCP_CLASS_POSTBOUNDLTR to bind the string to left-to-right reading order after the string.
GCPCLASS_POSTBOUNDRTL | Set lpClass[0] to GCP_CLASS_POSTBOUNDRTL to bind the string to right-to-left reading order after the string.

To force the layout of a character to be carried out in a specific way, preset the classification for the corresponding array element; the function leaves such preset classifications unchanged and computes classifications only for array elements that have been set to zero. Preset classifications are used only if the GCP_CLASSIN flag is set and the lpclass array is supplied.

If getFontLanguageInfo does not return GCP_REORDER for the current font, only the GCPCLASS_LATIN value is meaningful.

lpGlyphs
Pointer to the array that receives the values identifying the glyphs used for rendering the string or is NULL if glyph rendering is not needed. The number of glyphs in the array may be less than the number of characters in the original string if the string contains ligated glyphs. Also if reordering is required, the order of the glyphs may not be sequential.

This array is useful if more than one operation is being done on a string which has any form of ligation, kerning or order-switching. Using the values in this array for subsequent operations saves the time otherwise required to generate the glyph indices each time.

This array always contains glyph indices and the ETO_GLYPH_INDEX value must always be used when this array is used with the ExtTextOut function.

When GCP_LIGATE is used, you can limit the number of characters that will be ligated together. (In Arabic for example, three-character ligations are common). This is done by setting the maximum required in lpGcpResults->lpGlyphs[0]. If no maximum is required, you should set this field to zero.

For languages such as Arabic, where GetFontLanguageInfo returns the GCP_GLYPHSHAPE flag, the glyphs for a character will be different depending on whether the character is at the beginning, middle, or end of a word. Typically, the first character in the input string will also be the first character in a word, and the last character in the input string will be treated as the last character in a word. However, if the displayed string is a subset of the complete string, such as when displaying a section of scrolled text, this may not be true. In these cases, it is desirable to force the first or last characters to be shaped as not being initial or final forms. To do this, again, the first location in the lpGlyphs array is used by performing an OR operation of the ligation value above with the values GCPGLYPH_LINKBEFORE and/or GCPGLYPH_LINKAFTER. For example, a value of GCPGLYPH_LINKBEFORE | 2 means that two-character ligatures are the maximum required, and the first character in the string should be treated as if it is in the middle of a word.

nGlyphs
On input, this member must be set to the size of the arrays pointed to by the array pointer members. On output, this is set to the number of glyphs filled in, in the output arrays. If glyph substitution is not required (that is, each input character maps to exactly one glyph), this member is the same as it is on input.
nMaxFit
Number of characters that fit within the extents specified by the nMaxExtent parameter of the GetCharacterPlacement function. If the GCP_MAXEXTENT or GCP_JUSTIFY value is set, this value may be less than the number of characters in the original string. This member is set regardless of whether the GCP_MAXEXTENT or GCP_JUSTIFY value is specified. Unlike nGlyphs, which specifies the number of output glyphs, nMaxFit refers to the number of characters from the input string. For Latin SBCS languages, this will be the same.

Remarks

Whether the lpGlyphs, lpOutString, or neither is required depends on the results of the GetFontLanguageInfo call.

In the case of a font for a language such as English, in which none of the GCP_DBCS, GCP_REORDER, GCP_GLYPHSHAPE, GCP_LIGATE, GCP_DIACRITIC, or GCP_KASHIDA flags are returned, neither of the arrays is required for proper operation. (Though not required, they can still be used. If the lpOutString array is used, it will be exactly the same as the lpInputString passed to GetCharacterPlacement.) Note, however, that if GCP_MAXEXTENT is used, then lpOutString will contain the truncated string if it is used, NOT an exact copy of the original.

In the case of fonts for languages such as Hebrew, which DO have reordering but do not typically have extra glyph shapes, lpOutString should be used. This will give the string on the screen-readable order. However, the lpGlyphs array is not typically needed. (Hebrew can have extra glyphs, if the font is a TrueType/Open font.)

In the case of languages such as Thai or Arabic, in which GetFontLanguageInfo returns the GCP_GLYPHSHAPE flag, the lpOutString will give the display-readable order of the string passed to GetCharacterPlacement, but the values will still be the unshaped characters. For proper display, the lpGlyphs array must be used.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, ExtTextOut, GetCharacterPlacement, GetFontLanguageInfo


GLYPHMETRICS

The GLYPHMETRICS structure contains information about the placement and orientation of a glyph in a character cell.

typedef struct _GLYPHMETRICS {
  UINT  gmBlackBoxX;
  UINT  gmBlackBoxY;
  POINT gmptGlyphOrigin;
  short gmCellIncX;
  short gmCellIncY;
} GLYPHMETRICS, *LPGLYPHMETRICS;

Members

gmBlackBoxX
Specifies the width of the smallest rectangle that completely encloses the glyph (its black box).
gmBlackBoxY
Specifies the height of the smallest rectangle that completely encloses the glyph (its black box).
gmptGlyphOrigin
Specifies the x- and y-coordinates of the upper left corner of the smallest rectangle that completely encloses the glyph.
gmCellIncX
Specifies the horizontal distance from the origin of the current character cell to the origin of the next character cell.
gmCellIncY
Specifies the vertical distance from the origin of the current character cell to the origin of the next character cell.

Remarks

Values in the GLYPHMETRICS structure are specified in device units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetGlyphOutline


GLYPHSET

The GLYPHSET structure contains information about a range of Unicode code points.

typedef struct tagGLYPHSET {
  DWORD    cbThis;
  DWORD    flAccel;
  DWORD    cGlyphsSupported;
  DWORD    cRanges;
  WCRANGE  ranges[1];
} GLYPHSET, *PGLYPHSET;

Members

cbThis
Size, in bytes, of this structure.
flAccel
Flags describing the maximum size of the glyph indices. This member can be the following value.
Value | Meaning
GS_8BIT_INDICES | Treat glyph indices as 8-bit wide values. Otherwise, they are 16-bit wide values.

cGlyphsSupported
Total number of Unicode code points supported in the font.
cRanges
Total number of Unicode ranges in ranges.
ranges
Array of Unicode ranges that are supported in the font.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetFontUnicodeRanges, WCRANGE


KERNINGPAIR

The KERNINGPAIR structure defines a kerning pair.

typedef struct tagKERNINGPAIR {
  WORD  wFirst;
  WORD  wSecond;
  int  iKernAmount;
} KERNINGPAIR, *LPKERNINGPAIR;

Members

wFirst
Specifies the character code for the first character in the kerning pair.
wSecond
Specifies the character code for the second character in the kerning pair.
iKernAmount
Specifies the amount this pair will be kerned if they appear side by side in the same font and size. This value is typically negative, because pair kerning usually results in two characters being set more tightly than normal. The value is specified in logical units—that is, it depends on the current mapping mode.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetKerningPairs


LOGFONT

The LOGFONT structure defines the attributes of a font.

typedef struct tagLOGFONT {
  LONG lfHeight;
  LONG lfWidth;
  LONG lfEscapement;
  LONG lfOrientation;
  LONG lfWeight;
  BYTE lfItalic;
  BYTE lfUnderline;
  BYTE lfStrikeOut;
  BYTE lfCharSet;
  BYTE lfOutPrecision;
  BYTE lfClipPrecision;
  BYTE lfQuality;
  BYTE lfPitchAndFamily;
  TCHAR lfFaceName[LF_FACESIZE];
} LOGFONT, *PLOGFONT;

Members

lfHeight
Specifies the height, in logical units, of the font's character cell or character. The character height value (also known as the em height) is the character cell height value minus the internal-leading value. The font mapper interprets the value specified in lfHeight in the following manner.
Value | Meaning
> 0 | The font mapper transforms this value into device units and matches it against the cell height of the available fonts.
0 | The font mapper uses a default height value when it searches for a match.
< 0 | The font mapper transforms this value into device units and matches its absolute value against the character height of the available fonts.

For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size.

This mapping occurs when the font is used for the first time.

For the MM_TEXT mapping mode, you can use the following formula to specify a height for a font with a specified point size:

lfHeight = -MulDiv(PointSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
lfWidth
Specifies the average width, in logical units, of characters in the font. If lfWidth is zero, the aspect ratio of the device is matched against the digitization aspect ratio of the available fonts to find the closest match, determined by the absolute value of the difference.
lfEscapement
Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text.

Windows NT/2000 or later: When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters.

When the graphics mode is set to GM_COMPATIBLE, lfEscapement specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.

Windows 95: The lfEscapement member specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.

lfOrientation
Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device.
lfWeight
Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.

The following values are defined for convenience.
Value | Weight
FW_DONTCARE | 0
FW_THIN | 100
FW_EXTRALIGHT | 200
FW_ULTRALIGHT | 200
FW_LIGHT | 300
FW_NORMAL | 400
FW_REGULAR | 400
FW_MEDIUM | 500
FW_SEMIBOLD | 600
FW_DEMIBOLD | 600
FW_BOLD | 700
FW_EXTRABOLD | 800
FW_ULTRABOLD | 800
FW_HEAVY | 900
FW_BLACK | 900

lfItalic
Specifies an italic font if set to TRUE.
lfUnderline
Specifies an underlined font if set to TRUE.
lfStrikeOut
Specifies a strikeout font if set to TRUE.
lfCharSet
Specifies the character set. The following values are predefined.

ANSI_CHARSET
BALTIC_CHARSET
CHINESEBIG5_CHARSET
DEFAULT_CHARSET
EASTEUROPE_CHARSET
GB2312_CHARSET
GREEK_CHARSET
HANGUL_CHARSET
MAC_CHARSET
OEM_CHARSET
RUSSIAN_CHARSET
SHIFTJIS_CHARSET
SYMBOL_CHARSET
TURKISH_CHARSET

Windows NT/2000 or Middle-Eastern Windows 3.1 or later:
HEBREW_CHARSET
ARABIC_CHARSET
Windows NT/2000 or Thai Windows 3.1 or later:
THAI_CHARSET

The OEM_CHARSET value specifies a character set that is operating-system dependent.

Windows 95/98/Me: You can use the DEFAULT_CHARSET value to allow the name and size of a font to fully describe the logical font. If the specified font name does not exist, a font from any character set can be substituted for the specified font, so you should use DEFAULT_CHARSET sparingly to avoid unexpected results.

Windows NT/2000 or later: DEFAULT_CHARSET is set to a value based on the current system locale. For example, when the system locale is English (United States), it is set as ANSI_CHARSET.

Fonts with other character sets may exist in the operating system. If an application uses a font with an unknown character set, it should not attempt to translate or interpret strings that are rendered with that font.

This parameter is important in the font mapping process. To ensure consistent results, specify a specific character set. If you specify a typeface name in the lfFaceName member, make sure that the lfCharSet value matches the character set of the typeface specified in lfFaceName.

lfOutPrecision
Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It can be one of the following values.
Value | Meaning
OUT_CHARACTER_PRECIS | Not used.
OUT_DEFAULT_PRECIS | Specifies the default font mapper behavior.
OUT_DEVICE_PRECIS | Instructs the font mapper to choose a Device font when the system contains multiple fonts with the same name.
OUT_OUTLINE_PRECIS | Windows NT/2000 or later: This value instructs the font mapper to choose from TrueType and other outline-based fonts.
OUT_RASTER_PRECIS | Instructs the font mapper to choose a raster font when the system contains multiple fonts with the same name.
OUT_STRING_PRECIS | This value is not used by the font mapper, but it is returned when raster fonts are enumerated.
OUT_STROKE_PRECIS Windows NT/2000 or later: This value is not used by the font mapper, but it is returned when TrueType, other outline-based fonts, and vector fonts are enumerated.

Windows 95:This value is used to map vector fonts, and is returned when TrueType or vector fonts are enumerated.

OUT_TT_ONLY_PRECIS | Instructs the font mapper to choose from only TrueType fonts. If there are no TrueType fonts installed in the system, the font mapper returns to default behavior.
OUT_TT_PRECIS | Instructs the font mapper to choose a TrueType font when the system contains multiple fonts with the same name.

Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the operating system contains more than one font with a specified name. For example, if an operating system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. Specifying OUT_TT_ONLY_PRECIS forces the font mapper to choose a TrueType font, even if it must substitute a TrueType font of another name.

lfClipPrecision
Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be one or more of the following values.
Value | Meaning
CLIP_DEFAULT_PRECIS | Specifies default clipping behavior.
CLIP_CHARACTER_PRECIS | Not used.
CLIP_STROKE_PRECIS Not used by the font mapper, but is returned when raster, vector, or TrueType fonts are enumerated.

Windows NT/2000 or later: For compatibility, this value is always returned when enumerating fonts.
CLIP_MASK | Not used.
CLIP_EMBEDDED | You must specify this flag to use an embedded read-only font.
CLIP_LH_ANGLES When this value is used, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed.

If not used, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system.

For more information about the orientation of coordinate systems, see the description of the nOrientation parameter
CLIP_TT_ALWAYS | Not used.

lfQuality
Specifies the output quality. The output quality defines how carefully the graphics device interface (GDI) must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values.
Value | Meaning
ANTIALIASED_QUALITY Windows NT 4.0 and later: Font is always antialiased if the font supports it and the size of the font is not too small or too large.

Windows 95 and later: In addition to the comments for Windows NT, the display must greater than 8-bit color, it must be a single plane device, it cannot be a palette display, and it cannot be in a multiple display monitor setup. In addition, you must select a TrueType font into a screen DC prior to using it in a DIBSection, otherwise antialiasing does not occur.
CLEARTYPE_QUALITY | Whistler: If set, text is rendered (when possible) using ClearType antialiasing method. See Remarks for more information.
DEFAULT_QUALITY | Appearance of the font does not matter.
DRAFT_QUALITY | Appearance of the font is less important than when PROOF_QUALITY is used. For GDI raster fonts, scaling is enabled, which means that more font sizes are available, but the quality may be lower. Bold, italic, underline, and strikeout fonts are synthesized if necessary.
NONANTIALIASED_QUALITY | Windows 95, Windows NT 4.0, and Windows 2000 or later: Font is never antialiased.
PROOF_QUALITY | Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Although the chosen font size may not be mapped exactly when PROOF_QUALITY is used, the quality of the font is high and there is no distortion of appearance. Bold, italic, underline, and strikeout fonts are synthesized if necessary.

If neither ANTIALIASED_QUALITY nor NONANTIALIASED_QUALITY is selected, the font is antialiased only if the user chooses smooth screen fonts in Control Panel.

lfPitchAndFamily
Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be one of the following values.

DEFAULT_PITCH
FIXED_PITCH
VARIABLE_PITCH

Bits 4 through 7 of the member specify the font family and can be one of the following values.

FF_DECORATIVE
FF_DONTCARE
FF_MODERN
FF_ROMAN
FF_SCRIPT
FF_SWISS

The proper value can be obtained by using the Boolean OR operator to join one pitch constant with one family constant.

Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface desired is not available. The values for font families are as follows.
Value | Meaning
FF_DECORATIVE | Novelty fonts. Old English is an example.
FF_DONTCARE | Don't care or don't know.
FF_MODERN | Fonts with constant stroke width (monospace), with or without serifs. Monospace fonts are usually modern. Pica, Elite, and CourierNew® are examples.
FF_ROMAN | Fonts with variable stroke width (proportional) and with serifs. MS® Serif is an example.
FF_SCRIPT | Fonts designed to look like handwriting. Script and Cursive are examples.
FF_SWISS | Fonts with variable stroke width (proportional) and without serifs. MS® Sans Serif is an example.

lfFaceName
A null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts. If lfFaceName is an empty string, GDI uses the first font that matches the other specified attributes.

Remarks

Whistler: The following situations do not support ClearType antialiasing:

  • Text is rendered on a printer.
  • Display set for 256 colors or less.
  • Text is rendered to a terminal server client.
  • The font is not a TrueType font or an OpenType font with TrueType outlines. For example, the following do not support ClearType antialiasing: Type 1 fonts, Postscript OpenType fonts without TrueType outlines, bitmap fonts, vector fonts, and device fonts.
  • The font has tuned embedded bitmaps, for any font sizes that contain the embedded bitmaps. For example, this occurs commonly in East Asian fonts.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, CreateFont, CreateFontIndirect, EnumFontFamilies


MAT2

The MAT2 structure contains the values for a transformation matrix used by the GetGlyphOutline function.

typedef struct _MAT2 {
  FIXED eM11;
  FIXED eM12;
  FIXED eM21;
  FIXED eM22;
} MAT2, *LPMAT2;

Members

eM11
Specifies a fixed-point value for the M11 component of a 3 by 3 transformation matrix.
eM12
Specifies a fixed-point value for the M12 component of a 3 by 3 transformation matrix.
eM21
Specifies a fixed-point value for the M21 component of a 3 by 3 transformation matrix.
eM22
Specifies a fixed-point value for the M22 component of a 3 by 3 transformation matrix.

Remarks

The identity matrix produces a transformation in which the transformed graphical object is identical to the source object. In the identity matrix, the value of eM11 is 1, the value of eM12 is zero, the value of eM21 is zero, and the value of eM22 is 1.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetGlyphOutline


NEWTEXTMETRIC

The NEWTEXTMETRIC structure contains data that describes a physical font.

typedef struct tagNEWTEXTMETRIC {
  LONG   tmHeight;
  LONG   tmAscent;
  LONG   tmDescent;
  LONG   tmInternalLeading;
  LONG   tmExternalLeading;
  LONG   tmAveCharWidth;
  LONG   tmMaxCharWidth;
  LONG   tmWeight;
  LONG   tmOverhang;
  LONG   tmDigitizedAspectX;
  LONG   tmDigitizedAspectY;
  TCHAR  tmFirstChar;
  TCHAR  tmLastChar;
  TCHAR  tmDefaultChar;
  TCHAR  tmBreakChar;
  BYTE   tmItalic;
  BYTE   tmUnderlined;
  BYTE   tmStruckOut;
  BYTE   tmPitchAndFamily;
  BYTE   tmCharSet;
  DWORD  ntmFlags;
  UINT   ntmSizeEM;
  UINT   ntmCellHeight;
  UINT   ntmAvgWidth;
} NEWTEXTMETRIC, *PNEWTEXTMETRIC;

Members

tmHeight
Specifies the height (ascent + descent) of characters.
tmAscent
Specifies the ascent (units above the base line) of characters.
tmDescent
Specifies the descent (units below the base line) of characters.
tmInternalLeading
Specifies the amount of leading (space) inside the bounds set by the tmHeight member. Accent marks and other diacritical characters may occur in this area. The designer may set this member to zero.
tmExternalLeading
Specifies the amount of extra leading (space) that the application adds between rows. Since this area is outside the font, it contains no marks and is not altered by text output calls in either OPAQUE or TRANSPARENT mode. The designer may set this member to zero.
tmAveCharWidth
Specifies the average width of characters in the font (generally defined as the width of the letter x). This value does not include overhang required for bold or italic characters.
tmMaxCharWidth
Specifies the width of the widest character in the font.
tmWeight
Specifies the weight of the font.
tmOverhang
Specifies the extra width per string that may be added to some synthesized fonts. When synthesizing some attributes, such as bold or italic, graphics device interface (GDI) or a device may have to add width to a string on both a per-character and per-string basis. For example, GDI makes a string bold by expanding the spacing of each character and overstriking by an offset value; it italicizes a font by shearing the string. In either case, there is an overhang past the basic string. For bold strings, the overhang is the distance by which the overstrike is offset. For italic strings, the overhang is the amount the top of the font is sheared past the bottom of the font.

The tmOverhang member enables the application to determine how much of the character width returned by a GetTextExtentPoint32 function call on a single character is the actual character width and how much is the per-string extra width. The actual width is the extent minus the overhang.

tmDigitizedAspectX
Specifies the horizontal aspect of the device for which the font was designed.
tmDigitizedAspectY
Specifies the vertical aspect of the device for which the font was designed. The ratio of the tmDigitizedAspectX and tmDigitizedAspectY members is the aspect ratio of the device for which the font was designed.
tmFirstChar
Specifies the value of the first character defined in the font.
tmLastChar
Specifies the value of the last character defined in the font.
tmDefaultChar
Specifies the value of the character to be substituted for characters that are not in the font.
tmBreakChar
Specifies the value of the character to be used to define word breaks for text justification.
tmItalic
Specifies an italic font if it is nonzero.
tmUnderlined
Specifies an underlined font if it is nonzero.
tmStruckOut
Specifies a strikeout font if it is nonzero.
tmPitchAndFamily
Specifies the pitch and family of the selected font. The low-order bit (bit 0) specifies the pitch of the font. If it is 1, the font is variable pitch (or proportional). If it is 0, the font is fixed pitch (or monospace). Bits 1 and 2 specify the font type. If both bits are 0, the font is a raster font; if bit 1 is 1 and bit 2 is 0, the font is a vector font; if bit 1 is 0 and bit 2 is set, or if both bits are 1, the font is some other type. Bit 3 is 1 if the font is a device font; otherwise, it is 0.

The four high-order bits designate the font family. The tmPitchAndFamily member can be combined with the hexadecimal value 0xF0 by using the bitwise AND operator and can then be compared with the font family names for an identical match. For more information about the font families, see LOGFONT.

tmCharSet
Specifies the character set of the font.
ntmFlags
Specifies whether the font is italic, underscored, outlined, bold, and so forth. May be any reasonable combination of the following values.
Bit | Name | Meaning
0 | NTM_ITALIC | italic
5 | NTM_BOLD | bold
8 | NTM_REGULAR | regular
16 | NTM_NONNEGATIVE_AC | Windows 2000 or later: no glyph in a font at any size has a negative A or C space.
17 | NTM_PS_OPENTYPE | Windows 2000 or later: PostScript OpenType font
18 | NTM_TT_OPENTYPE | Windows 2000 or later: TrueType OpenType font
19 | NTM_MULTIPLEMASTER | Windows 2000 or later: multiple master font
20 | NTM_TYPE1 | Windows 2000 or later: Type 1 font
21 | NTM_DSIG | Windows 2000 or later: font with a digital signature. This allows traceability and ensures that the font has been tested and is not corrupted

ntmSizeEM
Specifies the size of the em square for the font. This value is in notional units (that is, the units for which the font was designed).
ntmCellHeight
Specifies the height, in notional units, of the font. This value should be compared with the value of the ntmSizeEM member.
ntmAvgWidth
Specifies the average width of characters in the font, in notional units. This value should be compared with the value of the ntmSizeEM member.

Remarks

The last four members of the NEWTEXTMETRIC structure are not included in the TEXTMETRIC structure; in all other respects, the structures are identical.

The sizes in the NEWTEXTMETRIC structure are typically specified in logical units; that is, they depend on the current mapping mode of the display context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, EnumFontFamilies, GetTextExtentPoint32, GetTextMetrics, LOGFONT


NEWTEXTMETRICEX

The NEWTEXTMETRICEX structure contains information about a physical font.

typedef struct tagNEWTEXTMETRICEX {
  NEWTEXTMETRIC  ntmTm;
  FONTSIGNATURE  ntmFontSig;
} NEWTEXTMETRICEX;

Members

ntmTm
Specifies a NEWTEXTMETRIC structure.
ntmFontSig
Specifies a FONTSIGNATURE structure indicating the coverage of the font.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, NEWTEXTMETRIC, FONTSIGNATURE


OUTLINETEXTMETRIC

The OUTLINETEXTMETRIC structure contains metrics describing a TrueType font.

typedef struct _OUTLINETEXTMETRIC {
  UINT   otmSize;
  TEXTMETRIC otmTextMetrics;
  BYTE   otmFiller;
  PANOSE otmPanoseNumber;
  UINT   otmfsSelection;
  UINT   otmfsType;
  int    otmsCharSlopeRise;
  int    otmsCharSlopeRun;
  int    otmItalicAngle;
  UINT   otmEMSquare;
  int    otmAscent;
  int    otmDescent;
  UINT   otmLineGap;
  UINT   otmsCapEmHeight;
  UINT   otmsXHeight;
  RECT   otmrcFontBox;
  int    otmMacAscent;
  int    otmMacDescent;
  UINT   otmMacLineGap;
  UINT   otmusMinimumPPEM;
  POINT  otmptSubscriptSize;
  POINT  otmptSubscriptOffset;
  POINT  otmptSuperscriptSize;
  POINT  otmptSuperscriptOffset;
  UINT   otmsStrikeoutSize;
  int    otmsStrikeoutPosition;
  int    otmsUnderscoreSize;
  int    otmsUnderscorePosition;
  PSTR   otmpFamilyName;
  PSTR   otmpFaceName;
  PSTR   otmpStyleName;
  PSTR   otmpFullName;
} OUTLINETEXTMETRIC, *POUTLINETEXTMETRIC;

Members

otmSize
Specifies the size, in bytes, of the OUTLINETEXTMETRIC structure.
otmTextMetrics
Specifies a TEXTMETRIC structure containing further information about the font.
otmFiller
Specifies a value that causes the structure to be byte aligned.
otmPanoseNumber
Specifies the PANOSE number for this font.
otmfsSelection
Specifies the nature of the font pattern. This member can be a combination of the following bits.
Bit | Meaning
0 | Italic
1 | Underscore
2 | Negative
3 | Outline
4 | Strikeout
5 | Bold

otmfsType
Specifies whether the font is licensed. Licensed fonts must not be modified or exchanged. If bit 1 is set, the font may not be embedded in a document. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read-only.
otmsCharSlopeRise
Specifies the slope of the cursor. This value is 1 if the slope is vertical. Applications can use this value and the value of the otmsCharSlopeRun member to create an italic cursor that has the same slope as the main italic angle (specified by the otmItalicAngle member).
otmsCharSlopeRun
Specifies the slope of the cursor. This value is zero if the slope is vertical. Applications can use this value and the value of the otmsCharSlopeRise member to create an italic cursor that has the same slope as the main italic angle (specified by the otmItalicAngle member).
otmItalicAngle
Specifies the main italic angle of the font, in tenths of a degree counterclockwise from vertical. Regular (roman) fonts have a value of zero. Italic fonts typically have a negative italic angle (that is, they lean to the right).
otmEMSquare
Specifies the number of logical units defining the x- or y-dimension of the em square for this font. (The number of units in the x- and y-directions are always the same for an em square.)
otmAscent
Specifies the maximum distance characters in this font extend above the base line. This is the typographic ascent for the font.
otmDescent
Specifies the maximum distance characters in this font extend below the base line. This is the typographic descent for the font.
otmLineGap
Specifies typographic line spacing.
otmsCapEmHeight
Not supported.
otmsXHeight
Not supported.
otmrcFontBox
Specifies the bounding box for the font.
otmMacAscent
Specifies the maximum distance characters in this font extend above the base line for the Macintosh® computer.
otmMacDescent
Specifies the maximum distance characters in this font extend below the base line for the Macintosh computer.
otmMacLineGap
Specifies line-spacing information for the Macintosh computer.
otmusMinimumPPEM
Specifies the smallest recommended size for this font, in pixels per em-square.
otmptSubscriptSize
Specifies the recommended horizontal and vertical size for subscripts in this font.
otmptSubscriptOffset
Specifies the recommended horizontal and vertical offset for subscripts in this font. The subscript offset is measured from the character origin to the origin of the subscript character.
otmptSuperscriptSize
Specifies the recommended horizontal and vertical size for superscripts in this font.
otmptSuperscriptOffset
Specifies the recommended horizontal and vertical offset for superscripts in this font. The superscript offset is measured from the character base line to the base line of the superscript character.
otmsStrikeoutSize
Specifies the width of the strikeout stroke for this font. Typically, this is the width of the em dash for the font.
otmsStrikeoutPosition
Specifies the position of the strikeout stroke relative to the base line for this font. Positive values are above the base line and negative values are below.
otmsUnderscoreSize
Specifies the thickness of the underscore character for this font.
otmsUnderscorePosition
Specifies the position of the underscore character for this font.
otmpFamilyName
Specifies the offset from the beginning of the structure to a string specifying the family name for the font.
otmpFaceName
Specifies the offset from the beginning of the structure to a string specifying the typeface name for the font. (This typeface name corresponds to the name specified in the LOGFONT structure.)
otmpStyleName
Specifies the offset from the beginning of the structure to a string specifying the style name for the font.
otmpFullName
Specifies the offset from the beginning of the structure to a string specifying the full name for the font. This name is unique for the font and often contains a version number or other identifying information.

Remarks

The sizes returned in OUTLINETEXTMETRIC are specified in logical units; that is, they depend on the current mapping mode of the specified display context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, GetOutlineTextMetrics, LOGFONT, TEXTMETRIC


PANOSE

The PANOSE structure describes the PANOSE font-classification values for a TrueType font. These characteristics are then used to associate the font with other fonts of similar appearance but different names.

typedef struct tagPANOSE {
  BYTE bFamilyType;
  BYTE bSerifStyle;
  BYTE bWeight;
  BYTE bProportion;
  BYTE bContrast;
  BYTE bStrokeVariation;
  BYTE bArmStyle;
  BYTE bLetterform;
  BYTE bMidline;
  BYTE bXHeight;
} PANOSE, *LPPANOSE;

Members

bFamilyType
For Latin fonts, bFamilyType can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_FAMILY_TEXT_DISPLAY | Text and display
PAN_FAMILY_SCRIPT | Script
PAN_FAMILY_DECORATIVE | Decorative
PAN_FAMILY_PICTORIAL | Pictorial

bSerifStyle
Specifies the serif style. For Latin fonts, bSerifStyle can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_SERIF_COVE | Cove
PAN_SERIF_OBTUSE_COVE | Obtuse cove
PAN_SERIF_SQUARE_COVE | Square cove
PAN_SERIF_OBTUSE_SQUARE_COVE | Obtuse square cove
PAN_SERIF_SQUARE | Square
PAN_SERIF_THIN | Thin
PAN_SERIF_BONE | Bone
PAN_SERIF_EXAGGERATED | Exaggerated
PAN_SERIF_TRIANGLE | Triangle
PAN_SERIF_NORMAL_SANS | Normal sans serif
PAN_SERIF_OBTUSE_SANS | Obtuse sans serif
PAN_SERIF_PERP_SANS | Perp sans serif
PAN_SERIF_FLARED | Flared
PAN_SERIF_ROUNDED | Rounded

bWeight
For Latin fonts, bWeight can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_WEIGHT_VERY_LIGHT | Very light
PAN_WEIGHT_LIGHT | Light
PAN_WEIGHT_THIN | Thin
PAN_WEIGHT_BOOK | Book
PAN_WEIGHT_MEDIUM | Medium
PAN_WEIGHT_DEMI | Demibold
PAN_WEIGHT_BOLD | Bold
PAN_WEIGHT_HEAVY | Heavy
PAN_WEIGHT_BLACK | Black
PAN_WEIGHT_NORD | Nord

bProportion
For Latin fonts, bProportion can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_PROP_OLD_STYLE | Old style
PAN_PROP_MODERN | Modern
PAN_PROP_EVEN_WIDTH | Even width
PAN_PROP_EXPANDED | Expanded
PAN_PROP_CONDENSED | Condensed
PAN_PROP_VERY_EXPANDED | Very expanded
PAN_PROP_VERY_CONDENSED | Very condensed
PAN_PROP_MONOSPACED | Monospaced

bContrast
For Latin fonts, bContrast can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_CONTRAST_NONE | None
PAN_CONTRAST_VERY_LOW | Very low
PAN_CONTRAST_LOW | Low
PAN_CONTRAST_MEDIUM_LOW | Medium low
PAN_CONTRAST_MEDIUM | Medium
PAN_CONTRAST_MEDIUM_HIGH | Medium high
PAN_CONTRAST_HIGH | High
PAN_CONTRAST_VERY_HIGH | Very high

bStrokeVariation
For Latin fonts, bStrokeVariation can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_STROKE_GRADUAL_DIAG | Gradual/diagonal
PAN_STROKE_GRADUAL_TRAN | Gradual/transitional
PAN_STROKE_GRADUAL_VERT | Gradual/vertical
PAN_STROKE_GRADUAL_HORZ | Gradual/horizontal
PAN_STROKE_RAPID_VERT | Rapid/vertical
PAN_STROKE_RAPID_HORZ | Rapid/horizontal
PAN_STROKE_INSTANT_VERT | Instant/vertical

bArmStyle
For Latin fonts, bArmStyle can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_STRAIGHT_ARMS_HORZ | Straight arms/horizontal
PAN_STRAIGHT_ARMS_WEDGE | Straight arms/wedge
PAN_STRAIGHT_ARMS_VERT | Straight arms/vertical
PAN_STRAIGHT_ARMS_SINGLE_SERIF | Straight arms/single-serif
PAN_STRAIGHT_ARMS_DOUBLE_SERIF | Straight arms/double-serif
PAN_BENT_ARMS_HORZ | Nonstraight arms/horizontal
PAN_BENT_ARMS_WEDGE | Nonstraight arms/wedge
PAN_BENT_ARMS_VERT | Nonstraight arms/vertical
PAN_BENT_ARMS_SINGLE_SERIF | Nonstraight arms/single-serif
PAN_BENT_ARMS_DOUBLE_SERIF | Nonstraight arms/double-serif

bLetterform
For Latin fonts, bLetterform can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_LETT_NORMAL_CONTACT | Normal/contact
PAN_LETT_NORMAL_WEIGHTED | Normal/weighted
PAN_LETT_NORMAL_BOXED | Normal/boxed
PAN_LETT_NORMAL_FLATTENED | Normal/flattened
PAN_LETT_NORMAL_ROUNDED | Normal/rounded
PAN_LETT_NORMAL_OFF_CENTER | Normal/off center
PAN_LETT_NORMAL_SQUARE | Normal/square
PAN_LETT_OBLIQUE_CONTACT | Oblique/contact
PAN_LETT_OBLIQUE_WEIGHTED | Oblique/weighted
PAN_LETT_OBLIQUE_BOXED | Oblique/boxed
PAN_LETT_OBLIQUE_FLATTENED | Oblique/flattened
PAN_LETT_OBLIQUE_ROUNDED | Oblique/rounded
PAN_LETT_OBLIQUE_OFF_CENTER | Oblique/off center
PAN_LETT_OBLIQUE_SQUARE | Oblique/square

bMidline
For Latin fonts, bMidline can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_MIDLINE_STANDARD_TRIMMED | Standard/trimmed
PAN_MIDLINE_STANDARD_POINTED | Standard/pointed
PAN_MIDLINE_STANDARD_SERIFED | Standard/serifed
PAN_MIDLINE_HIGH_TRIMMED | High/trimmed
PAN_MIDLINE_HIGH_POINTED | High/pointed
PAN_MIDLINE_HIGH_SERIFED | High/serifed
PAN_MIDLINE_CONSTANT_TRIMMED | Constant/trimmed
PAN_MIDLINE_CONSTANT_POINTED | Constant/pointed
PAN_MIDLINE_CONSTANT_SERIFED | Constant/serifed
PAN_MIDLINE_LOW_TRIMMED | Low/trimmed
PAN_MIDLINE_LOW_POINTED | Low/pointed
PAN_MIDLINE_LOW_SERIFED | Low/serifed

bXHeight
For Latin fonts, bXHeight can have one of the following values.
Value | Meaning
PAN_ANY | Any
PAN_NO_FIT | No fit
PAN_XHEIGHT_CONSTANT_SMALL | Constant/small
PAN_XHEIGHT_CONSTANT_STD | Constant/standard
PAN_XHEIGHT_CONSTANT_LARGE | Constant/large
PAN_XHEIGHT_DUCKING_SMALL | Ducking/small
PAN_XHEIGHT_DUCKING_STD | Ducking/standard
PAN_XHEIGHT_DUCKING_LARGE | Ducking/large

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, , EXTLOGFONT, OUTLINETEXTMETRIC


POINTFX

The POINTFX structure contains the coordinates of points that describe the outline of a character in a TrueType font.

typedef struct tagPOINTFX {
  FIXED x;
  FIXED y;
} POINTFX, *LPPOINTFX;

Members

x
Specifies the x-component of a point on the outline of a TrueType character.
y
Specifies the y-component of a point on the outline of a TrueType character.

Remarks

The POINTFX structure is a member of the TTPOLYCURVE and TTPOLYGONHEADER structures. Values in the POINTFX structure are specified in device units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, FIXED, TTPOLYCURVE, TTPOLYGONHEADER


POLYTEXT

The POLYTEXT structure describes how the PolyTextOut function should draw a string of text.

typedef struct _POLYTEXT {
  int  x;
  int  y;
  UINT  n;
  LPCTSTR  lpstr;
  UINT  uiFlags;
  RECT  rcl;
  int  *pdx;
} POLYTEXT, *PPOLYTEXT;

Members

x
Specifies the horizontal reference point for the string. The string is aligned to this point using the current text-alignment mode.
y
Specifies the vertical reference point for the string. The string is aligned to this point using the current text-alignment mode.
n
Specifies the length of the string. For the ANSI function it is a BYTE count and for the Unicode function it is a WORD count. Note that for the ANSI function, characters in SBCS code pages take one byte each while most characters in DBCS code pages take two bytes; for the Unicode function, most currently defined Unicode characters (those in the Basic Multilingual Plane (BMP)) are one WORD while Unicode surrogates are two WORDs.
lpstr
Pointer to a string of text to be drawn by the PolyTextOut function.
uiFlags
Specifies whether the string is to be opaque or clipped and whether the string is accompanied by an array of character-width values. This member can be one or more of the following values.
Value | Meaning
ETO_OPAQUE | The rectangle for each string is to be opaqued with the current background color.
ETO_CLIPPED | Each string is to be clipped to its specified rectangle.

rcl
Specifies a rectangle structure that contains the dimensions of the opaquing or clipping rectangle. This member is ignored if neither of the ETO_OPAQUE nor the ETO_CLIPPED value is specified for the uiFlags member.
pdx
Pointer to an array containing the width value for each character in the string.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, PolyTextOut


RASTERIZER_STATUS

The RASTERIZER_STATUS structure contains information about whether TrueType is installed. This structure is filled when an application calls the GetRasterizerCaps function.

typedef struct _RASTERIZER_STATUS {
  short nSize;
  short wFlags;
  short nLanguageID;
} RASTERIZER_STATUS, *LPRASTERIZER_STATUS;

Members

nSize
Specifies the size, in bytes, of the RASTERIZER_STATUS structure.
wFlags
Specifies whether at least one TrueType font is installed and whether TrueType is enabled. This value is TT_AVAILABLE, TT_ENABLED, or both if TrueType is on the system.
nLanguageID
Specifies the language in the system's Setup.inf file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetRasterizerCaps


TEXTMETRIC

The TEXTMETRIC structure contains basic information about a physical font. All sizes are specified in logical units; that is, they depend on the current mapping mode of the display context.

typedef struct tagTEXTMETRIC {
  LONG tmHeight;
  LONG tmAscent;
  LONG tmDescent;
  LONG tmInternalLeading;
  LONG tmExternalLeading;
  LONG tmAveCharWidth;
  LONG tmMaxCharWidth;
  LONG tmWeight;
  LONG tmOverhang;
  LONG tmDigitizedAspectX;
  LONG tmDigitizedAspectY;
  TCHAR tmFirstChar;
  TCHAR tmLastChar;
  TCHAR tmDefaultChar;
  TCHAR tmBreakChar;
  BYTE tmItalic;
  BYTE tmUnderlined;
  BYTE tmStruckOut;
  BYTE tmPitchAndFamily;
  BYTE tmCharSet;
} TEXTMETRIC, *PTEXTMETRIC;

Members

tmHeight
Specifies the height (ascent + descent) of characters.
tmAscent
Specifies the ascent (units above the base line) of characters.
tmDescent
Specifies the descent (units below the base line) of characters.
tmInternalLeading
Specifies the amount of leading (space) inside the bounds set by the tmHeight member. Accent marks and other diacritical characters may occur in this area. The designer may set this member to zero.
tmExternalLeading
Specifies the amount of extra leading (space) that the application adds between rows. Since this area is outside the font, it contains no marks and is not altered by text output calls in either OPAQUE or TRANSPARENT mode. The designer may set this member to zero.
tmAveCharWidth
Specifies the average width of characters in the font (generally defined as the width of the letter x). This value does not include the overhang required for bold or italic characters.
tmMaxCharWidth
Specifies the width of the widest character in the font.
tmWeight
Specifies the weight of the font.
tmOverhang
Specifies the extra width per string that may be added to some synthesized fonts. When synthesizing some attributes, such as bold or italic, graphics device interface (GDI) or a device may have to add width to a string on both a per-character and per-string basis. For example, GDI makes a string bold by expanding the spacing of each character and overstriking by an offset value; it italicizes a font by shearing the string. In either case, there is an overhang past the basic string. For bold strings, the overhang is the distance by which the overstrike is offset. For italic strings, the overhang is the amount the top of the font is sheared past the bottom of the font.

The tmOverhang member enables the application to determine how much of the character width returned by a GetTextExtentPoint32 function call on a single character is the actual character width and how much is the per-string extra width. The actual width is the extent minus the overhang.

tmDigitizedAspectX
Specifies the horizontal aspect of the device for which the font was designed.
tmDigitizedAspectY
Specifies the vertical aspect of the device for which the font was designed. The ratio of the tmDigitizedAspectX and tmDigitizedAspectY members is the aspect ratio of the device for which the font was designed.
tmFirstChar
Specifies the value of the first character defined in the font.
tmLastChar
Specifies the value of the last character defined in the font.
tmDefaultChar
Specifies the value of the character to be substituted for characters not in the font.
tmBreakChar
Specifies the value of the character that will be used to define word breaks for text justification.
tmItalic
Specifies an italic font if it is nonzero.
tmUnderlined
Specifies an underlined font if it is nonzero.
tmStruckOut
Specifies a strikeout font if it is nonzero.
tmPitchAndFamily
Specifies information about the pitch, the technology, and the family of a physical font.

The four low-order bits of this member specify information about the pitch and the technology of the font. A constant is defined for each of the four bits.
Constant | Meaning
TMPF_FIXED_PITCH | If this bit is set the font is a variable pitch font. If this bit is clear the font is a fixed pitch font. Note very carefully that those meanings are the opposite of what the constant name implies.
TMPF_VECTOR | If this bit is set the font is a vector font.
TMPF_TRUETYPE | If this bit is set the font is a TrueType font.
TMPF_DEVICE | If this bit is set the font is a device font.

An application should carefully test for qualities encoded in these low-order bits, making no arbitrary assumptions. For example, besides having their own bits set, TrueType and PostScript fonts set the TMPF_VECTOR bit. A monospace bitmap font has all of these low-order bits clear; a proportional bitmap font sets the TMPF_FIXED_PITCH bit. A Postscript printer device font sets the TMPF_DEVICE, TMPF_VECTOR, and TMPF_FIXED_PITCH bits.

The four high-order bits of tmPitchAndFamily designate the font's font family. An application can use the value 0xF0 and the bitwise AND operator to mask out the four low-order bits of tmPitchAndFamily, thus obtaining a value that can be directly compared with font family names to find an identical match. For information about font families, see the description of the LOGFONT structure.

tmCharSet
Specifies the character set of the font. The character set can be one of the following values.

ANSI_CHARSET
DEFAULT_CHARSET
SYMBOL_CHARSET
SHIFTJIS_CHARSET
HANGUL_CHARSET
GB2312_CHARSET
CHINESEBIG5_CHARSET
OEM_CHARSET
JOHAB_CHARSET
HEBREW_CHARSET
ARABIC_CHARSET
GREEK_CHARSET
TURKISH_CHARSET
VIETNAMESE_CHARSET
THAI_CHARSET
EASTEUROPE_CHARSET
RUSSIAN_CHARSET
MAC_CHARSET
BALTIC_CHARSET

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Fonts and Text Overview, Font and Text Structures, GetTextMetrics, GetTextExtentPoint32, LOGFONT


TTPOLYCURVE

The TTPOLYCURVE structure contains information about a curve in the outline of a TrueType character.

typedef struct tagTTPOLYCURVE {
  WORD    wType;
  WORD    cpfx;
  POINTFX apfx[1];
} TTPOLYCURVE, *LPTTPOLYCURVE;

Members

wType
Specifies the type of curve described by the structure. This member can be one of the following values.
Value | Meaning
TT_PRIM_LINE | Curve is a polyline.
TT_PRIM_QSPLINE | Curve is a quadratic Bézier spline.
TT_PRIM_CSPLINE | Curve is a cubic Bézier spline.

cpfx
Specifies the number of POINTFX structures in the array.
apfx
Specifies an array of POINTFX structures that define the polyline or Bézier spline.

Remarks

When an application calls the GetGlyphOutline function, a glyph outline for a TrueType character is returned in a TTPOLYGONHEADER structure, followed by as many TTPOLYCURVE structures as are required to describe the glyph. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point specified 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 (that is, quadratic b-splines) used by TrueType.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GetGlyphOutline, POINTFX, TTPOLYGONHEADER


TTPOLYGONHEADER

The TTPOLYGONHEADER structure specifies the starting position and type of a contour in a TrueType character outline.

typedef struct _TTPOLYGONHEADER {
  DWORD   cb;
  DWORD   dwType;
  POINTFX pfxStart;
} TTPOLYGONHEADER, *LPTTPOLYGONHEADER;

Members

cb
Specifies the number of bytes required by the TTPOLYGONHEADER structure and TTPOLYCURVE structure or structures required to describe the contour of the character.
dwType
Specifies the type of character outline returned. Currently, this value must be TT_POLYGON_TYPE.
pfxStart
Specifies the starting point of the contour in the character outline.

Remarks

Each TTPOLYGONHEADER structure is followed by one or more TTPOLYCURVE structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, POINTFX, TTPOLYCURVE


WCRANGE

The WCRANGE structure specifies a range of Unicode characters.

typedef struct tagWCRANGE {
  WCHAR  wcLow;
  USHORT cGlyphs;
} WCRANGE, *PWCRANGE,;

Members

wcLow
Low Unicode code point in the range of supported Unicode code points.
cGlyphs
Number of supported Unicode code points in this range.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Structures, GLYPHSET


Font and Text Messages

The following message is used with fonts.

WM_FONTCHANGE


WM_FONTCHANGE

An application sends the WM_FONTCHANGE message to all top-level windows in the system after changing the pool of font resources.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_FONTCHANGE,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Remarks

An application that adds or removes fonts from the system (for example, by using the AddFontResource or RemoveFontResource function) should send this message to all top-level windows.

To send the WM_FONTCHANGE message to all top-level windows, an application can call the SendMessage function with the hwnd parameter set to HWND_BROADCAST.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Fonts and Text Overview, Font and Text Messages, AddFontResource, RemoveFontResource


Lines and Curves

Lines and curves are used to draw graphics output on raster devices. As discussed in this overview, a line is a set of highlighted pixels on a raster display (or a set of dots on a printed page) identified by two points: a starting point and an ending point. A regular curve is a set of highlighted pixels on a raster display (or dots on a printed page) that defines the perimeter (or part of the perimeter) of a conic section. An irregular curve is a set of pixels that defines a curve that does not fit the perimeter of a conic section.

  • About Lines and Curves
  • Using Lines and Curves
  • Line and Curve Reference


About Lines and Curves

All types of Win32®-based applications use lines and curves to draw graphics output on raster devices. Computer-aided design (CAD) and drawing applications use lines and curves to outline objects, specify the centers of objects, the dimensions of objects, and so on. Spreadsheet applications use lines and curves to draw grids, charts, and graphs. Word processing applications use lines to create rules and borders on a page of text.

  • Lines
  • Curves
  • Combined Lines and Curves
  • Line and Curve Attributes


Lines

A line is a set of highlighted pixels on a raster display (or a set of dots on a printed page) identified by two points: a starting point and an ending point. The pixel located at the starting point is always included in the line, and the pixel located at the ending point is always excluded. (This kind of line is sometimes called inclusive-exclusive.)

When an application calls one of the Win32 line-drawing functions, graphics device interface (GDI), or in some cases a device driver, determines which pixels should be highlighted. GDI is a dynamic-link library (DLL) that processes graphics function calls from a Win32-based application and passes those calls to a device driver. A device driver is a DLL that receives input from GDI, converts the input to device commands, and passes those commands to the appropriate device. GDI uses a digital differential analyzer (DDA) to determine the set of pixels that define a line. A DDA determines the set of pixels by examining each point on the line and identifying those pixels on the display surface (or dots on a printed page) that correspond to the points. The following illustration shows a line, its starting point, its ending point, and the pixels highlighted by using a simple DDA.

The simplest and most common DDA is the Bresenham, or incremental, DDA. A modified version of this algorithm draws lines in Windows. The incremental DDA is noted for its simplicity, but it is also noted for its inaccuracy. Because it rounds off to the nearest integer value, it sometimes fails to represent the original line requested by the application. The DDA used by GDI does not round off to the nearest integer. As a result, this new DDA produces output that is sometimes much closer in appearance to the original line requested by the application.

Note If an application requires line output that cannot be achieved with the new DDA, it can draw its own lines by calling the LineDDA function and supplying a private DDA (LineDDAProc). However, the LineDDA function draws lines much slower than the Win32 line-drawing functions. Do not use this function within an application if speed is a primary concern.

An application can use the new DDA to draw single lines and multiple, connected line segments. An application can draw a single line by calling the LineTo function. This function draws a line from the current position up to, but not including, a specified ending point. An application can draw a series of connected line segments by calling the Polyline function, supplying an array of points that specify the ending point of each line segment. An application can draw multiple, disjointed series of connected line segments by calling the PolyPolyline function, supplying the required ending points.

The following illustration shows line output created by calling the LineTo, Polyline, and PolyPolyline functions.


Curves

A regular curve is a set of highlighted pixels on a raster display (or dots on a printed page) that define the perimeter (or part of the perimeter) of a conic section. An irregular curve is a set of pixels that define a curve that does not fit the perimeter of a conic section. In Win32-based applications, the ending point is excluded from a curve just as it is excluded from a line.

When an application calls one of the Win32 curve-drawing functions, GDI breaks the curve into a number of extremely small, discrete line segments. After determining the endpoints (starting point and ending point) for each of these line segments, GDI determines which pixels (or dots) define each line by applying its DDA.

An application can draw an ellipse or part of an ellipse by calling the Arc function. This function draws the curve within the perimeter of an invisible rectangle called a bounding rectangle. The size of the ellipse is specified by two invisible radials extending from the center of the rectangle to the sides of the rectangle. The following illustration shows an arc (part of an ellipse) drawn by using the Arc function.

When calling the Arc function, an application specifies the coordinates of the bounding rectangle and radials. The preceding illustration shows the rectangle and radials with dashed lines while the actual arc was drawn using a solid line.

When drawing the arc of another object, the application can call the SetArcDirection and GetArcDirection functions to control the direction (clockwise or counterclockwise) in which the object is drawn. The default direction for drawing arcs and other objects is counterclockwise.

In addition to drawing ellipses or parts of ellipses, Win32-based applications can draw irregular curves called Bézier curves. A Bézier curve is an irregular curve whose curvature is defined by four control points (p1, p2, p3, and p4). The control points p1 and p4 define the starting and ending points of the curve, and the control points p2 and p3 define the shape of the curve by marking points where the curve reverses orientation.

An application can draw irregular curves by calling the PolyBezier function, supplying the appropriate control points.


Combined Lines and Curves

In addition to drawing lines or curves, Win32-based applications can draw combinations of line and curve output by calling a single function. For example, an application can draw the outline of a pie chart by calling the AngleArc function.

The AngleArc function draws an arc along a circle's perimeter and draws a line connecting the starting point of the arc to the circle's center. In addition to using the AngleArc function, a Win32-based application can also combine line and irregular curve output by using the PolyDraw function.


Line and Curve Attributes

A device context (DC) contains attributes that affect line and curve output. The line and curve attributes include the current position, brush style, brush color, pen style, pen color, transformation, and so on.

The default current position for any DC is located at the point (0,0) in logical (or world) space. You can set these coordinates to a new position by calling the MoveToEx function and passing a new set of coordinates.

Note The Win32 API provides two sets of line- and curve-drawing functions. The first set retains the current position in a DC, and the second set alters the position. You can identify the functions that alter the current position by examining the function name. If the function name ends with the preposition "To", the function sets the current position to the ending point of the last line drawn (LineTo, ArcTo, PolylineTo, or PolyBezierTo). If the function name does not end with this preposition, it leaves the current position intact (Arc, Polyline, or PolyBezier).

The default brush is a solid white brush. An application can create a new brush by calling the CreateBrushIndirect function. After creating a brush, the application can select it into its DC by calling the SelectObject function. The Win32 API provides a complete set of functions to create, select, and alter the brush in an application's DC. For more information about these functions and about brushes in general, see Brushes.

The default pen is a cosmetic, solid black pen that is one pixel wide. An application can create a pen by using the ExtCreatePen function. After creating a pen, your application can select it into its DC by calling the SelectObject function. The Win32 API provides a complete set of functions to create, select, and alter the pen in an application's DC. For more information about these functions and about pens in general, see Pens.

The default transformation is the unity transformation (specified by the identity matrix). An application can specify a new transformation by calling the SetWorldTransform function. The Win32 API provides a complete set of functions to transform lines and curves by altering their width, location, and general appearance. For more information about these functions, Coordinate Spaces and Transformations.


Using Lines and Curves

You can use the line and curve functions to draw virtually any shape or object in the client area of an application window. This section illustrates how these functions can be used to draw markers or a pie chart.

  • Drawing markers
  • Drawing a pie chart


Drawing Markers

You can use the line functions to draw markers. A marker is a symbol centered over a point. Drawing applications use markers to designate starting points, ending points, and control points. Spreadsheet applications use markers to designate points of interest on a chart or graph.

In the following code sample, the application-defined Marker function creates a marker by using the MoveToEx and LineTo functions. These functions draw two intersecting lines, 20 pixels in length, centered over the cursor coordinates.

void Marker(LONG x, LONG y, HWND hwnd)
{
    HDC hdc;

    hdc = GetDC(hwnd);
        MoveToEx(hdc, (int) x - 10, (int) y, (LPPOINT) NULL);
        LineTo(hdc, (int) x + 10, (int) y);
        MoveToEx(hdc, (int) x, (int) y - 10, (LPPOINT) NULL);
        LineTo(hdc, (int) x, (int) y + 10);

    ReleaseDC(hwnd, hdc);
}

The system stores the coordinates of the cursor in the lParam parameter of the WM_LBUTTONDOWN message when the user presses the left mouse button. The following code demonstrates how an application gets these coordinates, determines whether they lie within its client area, and passes them to the Marker function to draw the marker.

// Line- and arc-drawing variables

static BOOL bCollectPoints;
static POINT ptMouseDown[32];
static int index;
POINTS ptTmp;
RECT rc;

    case WM_LBUTTONDOWN:

        if (bCollectPoints && index < 32)
        {
            // Create the region from the client area.

            GetClientRect(hwnd, &rc);
            hrgn = CreateRectRgn(rc.left, rc.top,
                rc.right, rc.bottom);

            ptTmp = MAKEPOINTS((POINTS FAR *) lParam);
            ptMouseDown[index].x = (LONG) ptTmp.x;
            ptMouseDown[index].y = (LONG) ptTmp.y;

            // Test for a hit in the client rectangle.

            if (PtInRegion(hrgn, ptMouseDown[index].x,
                    ptMouseDown[index].y))
            {
                // If a hit occurs, record the mouse coords.

                Marker(ptMouseDown[index].x, ptMouseDown[index].y,
                    hwnd);
                index++;
            }
        }
        break;


Drawing a Pie Chart

You can use the line and curve functions to draw a pie chart. The primary function used to draw pie charts is the AngleArc function, which requires you to supply the coordinates of the center of the pie, the radius of the pie, a start angle, and a sweep angle. Following is a dialog box that the user can use to enter these values.

Following is the resulting pie chart.

The dialog box template found in the application's resource script (.RC) file specifies characteristics of the preceding dialog box (its height, the controls it contains, and its style), as follows.

AngleArc DIALOG 6, 18, 160, 100
STYLE WS_DLGFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION
CAPTION "Pie Chart"
FONT 8, "MS Sans Serif"
BEGIN
    EDITTEXT   IDD_X, 18, 22, 25, 12, ES_AUTOHSCROLL
    LTEXT      "X", 102, 4, 24, 9, 8
    EDITTEXT   IDD_Y, 18, 39, 25, 12, ES_AUTOHSCROLL
    LTEXT      "Y", 104, 5, 42, 12, 8
    LTEXT      "Center", 105, 19, 11, 23, 8
    EDITTEXT   IDD_RADIUS, 103, 9, 32, 12, ES_AUTOHSCROLL
    EDITTEXT   IDD_STARTANGLE, 103, 31, 32, 12, ES_AUTOHSCROLL
    EDITTEXT   IDD_SWEEPANGLE, 103, 53, 32, 12, ES_AUTOHSCROLL
    LTEXT      "Radius", 109, 73, 11, 25, 8
    LTEXT      "Start Angle", 110, 59, 33, 42, 8
    LTEXT      "Sweep Angle", 111, 55, 55, 43, 8
    PUSHBUTTON "OK", IDD_OK, 9, 82, 40, 14
    PUSHBUTTON "Cancel", IDD_CANCEL, 110, 82, 40, 14
END

The dialog box procedure, found in the application's source file, retrieves data (center coordinates, arc radius, and start and sweep angles) by following these steps:

  1. The application-defined ClearBits function initializes the array that receives the user-input to zero.
  2. The application-defined GetStrLngth function retrieves the length of the string entered by the user.
  3. The application-defined RetrieveInput function retrieves the value entered by the user.

The following sample code shows the dialog box procedure.

void ClearBits(LPTSTR, int);
int GetStrLngth(LPTSTR);
DWORD RetrieveInput(LPTSTR, int);

BOOL CALLBACK ArcDlgProc(HWND hdlg, UINT uMsg, WPARAM wParam,
LPARAM lParam)
{
    CHAR chInput[4];    // receives control-window input
    int cch;            // array-size and count variable

    switch (uMsg)
    {
        case WM_INITDIALOG:
            return FALSE;

        case WM_COMMAND:
            switch (wParam)
            {
                // If the user pressed the OK button, retrieve the
                // data that was entered in the various AngleArc
                // controls.

                case IDD_OK:
                    // Retrieve the x-coordinate of the arc's center.

                    ClearBits(chInput, sizeof(chInput));
                    GetDlgItemText(hdlg, IDD_X, chInput,
                        sizeof(chInput));
                    cch = GetStrLngth(chInput);
                    nX = (int)RetrieveInput(chInput, cch);

                    // Retrieve the y-coordinate of the arc's center.

                    ClearBits(chInput, sizeof(chInput));
                    GetDlgItemText(hdlg, IDD_Y, chInput,
                        sizeof(chInput));
                    cch = GetStrLngth(chInput);
                    nY = (int)RetrieveInput(chInput, cch);

                    // Retrieve the radius of the arc.

                    ClearBits(chInput, sizeof(chInput));
                    GetDlgItemText(hdlg, IDD_RADIUS, chInput,
                        sizeof(chInput));
                    cch = GetStrLngth(chInput);
                    dwRadius = (DWORD) RetrieveInput(chInput, cch);

                    // Retrieve the start angle.

                    ClearBits(chInput, sizeof(chInput));
                    GetDlgItemText(hdlg, IDD_STARTANGLE, chInput,
                        sizeof(chInput));
                    cch = GetStrLngth(chInput);
                    xStartAngle = (float) RetrieveInput(chInput, cch);

                    // Retrieve the sweep angle.

                    ClearBits(chInput, sizeof(chInput));
                    GetDlgItemText(hdlg, IDD_SWEEPANGLE, chInput,
                        sizeof(chInput));
                    cch = GetStrLngth(chInput);
                    xSweepAngle = (float) RetrieveInput(chInput, cch);

                    EndDialog(hdlg, FALSE);
                    return TRUE;

                // If user presses the CANCEL button, close the
                // dialog box.

                case IDD_CANCEL:
                    EndDialog(hdlg, FALSE);
                    return TRUE;
            } // end switch (wParam)

            break;

        default:
            return FALSE;
    } // end switch (message)

    UNREFERENCED_PARAMETER(lParam);
}

void ClearBits(LPTSTR cArray, int iLength)
{
    int i;

    for (i = 0; i < iLength; i++)
        cArray[i] = 0;
}

int GetStrLngth(LPTSTR cArray)
{
    int i = 0;

    while (cArray[i++] != 0);
        return i - 1;
}

DWORD RetrieveInput(LPTSTR cArray, int iLength)
{
    int i, iTmp;
    double dVal, dCount;

    dVal = 0.0;
    dCount = (double) (iLength - 1);

    // Convert ASCII input to a floating-point value.

    for (i = 0; i < iLength; i++)
    {
        iTmp = cArray[i] - 0x30;
        dVal = dVal + (((double)iTmp) * pow(10.0, dCount--));
    }

    return (DWORD) dVal;
}

To draw each section of the pie chart, pass the values entered by the user to the AngleArc function. To fill the pie chart using the current brush, embed the call to AngleArc in a path bracket. The following code sample shows the defined path bracket and the call to AngleArc.

    int nX;
    int nY;
    DWORD dwRadius;
    float xStartAngle;
    float xSweepAngle;

    hdc = GetDC(hwnd);
    BeginPath(hdc);
    SelectObject(hdc, GetStockObject(GRAY_BRUSH));
    MoveToEx(hdc, nX, nY, (LPPOINT) NULL);
    AngleArc(hdc, nX, nY, dwRadius, xStartAngle, xSweepAngle);
    LineTo(hdc, nX, nY);
    EndPath(hdc);
    StrokeAndFillPath(hdc);
    ReleaseDC(hwnd, hdc);


Line and Curve Reference

The following elements are used with lines and curves.

  • Line and Curve Functions


Line and Curve Functions

The following functions are used with lines and curves.

Function | Description
AngleArc | Draws a line segment and an arc.
Arc | Draws an elliptical arc.
ArcTo | Draws an elliptical arc.
GetArcDirection | Retrieves the current arc direction for the specified device context.
LineDDA | Determines which pixels should be highlighted for a line defined by the specified starting and ending points.
LineDDAProc | An application-defined callback function used with the LineDDA function.
LineTo | Draws a line from the current position up to, but not including, the specified point.
MoveToEx | Updates the current position to the specified point and optionally returns the previous position.
PolyBezier | Draws one or more Bézier curves.
PolyBezierTo | Draws one or more Bézier curves.
PolyDraw | Draws a set of line segments and Bézier curves.
Polyline | Draws a series of line segments by connecting the points in the specified array.
PolylineTo | Draws one or more straight lines.
PolyPolyline | Draws multiple series of connected line segments.
SetArcDirection | Sets the drawing direction to be used for arc and rectangle functions.


AngleArc

The AngleArc function draws a line segment and an arc. 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.

BOOL AngleArc(
  HDC hdc,            // handle to device context
  int X,              // x-coordinate of circle's center
  int Y,              // y-coordinate of circle's center
  DWORD dwRadius,     // circle's radius
  FLOAT eStartAngle,  // arc's start angle
  FLOAT eSweepAngle   // arc's sweep angle
);

Parameters

hdc
[in] Handle to a device context.
X
[in] Specifies the logical x-coordinate of the center of the circle.
Y
[in] Specifies the logical y-coordinate of the center of the circle.
dwRadius
[in] Specifies the radius, in logical units, of the circle. This value must be positive.
eStartAngle
[in] Specifies the start angle, in degrees, relative to the x-axis.
eSweepAngle
[in] Specifies the sweep angle, in degrees, relative to the starting angle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The AngleArc function 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, AngleArc draws the line segment from the current position to the beginning of the arc.

The arc is drawn by constructing an imaginary circle around the specified center point with the specified radius. 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.

For an example, see Drawing a Pie Chart.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, Arc, ArcTo, MoveToEx


Arc

The Arc function draws an elliptical arc.

BOOL Arc(
  HDC hdc,         // handle to device context
  int nLeftRect,   // x-coord of rectangle's upper-left corner
  int nTopRect,    // y-coord of rectangle's upper-left corner
  int nRightRect,  // x-coord of rectangle's lower-right corner
  int nBottomRect, // y-coord of rectangle's lower-right corner
  int nXStartArc,  // x-coord of first radial ending point
  int nYStartArc,  // y-coord of first radial ending point
  int nXEndArc,    // x-coord of second radial ending point
  int nYEndArc     // y-coord of second radial ending point
);

Parameters

hdc
[in] Handle to the device context where drawing takes place.
nLeftRect
[in] Specifies the logical x-coordinate of the upper-left corner of the bounding rectangle.

Windows 95/98: The sum of nLeftRect plus nRightRect must be less than 32768.

nTopRect
[in] Specifies the logical y-coordinate of the upper-left corner of the bounding rectangle.

Windows 95/98: The sum of nTopRect plus nBottomRect must be less than 32768.

nRightRect
[in] Specifies the logical x-coordinate of the lower-right corner of the bounding rectangle.

Windows 95/98: The sum of nLeftRect plus nRightRect must be less than 32768.

nBottomRect
[in] Specifies the logical y-coordinate of the lower-right corner of the bounding rectangle.

Windows 95/98: The sum of nTopRect plus nBottomRect must be less than 32768.

nXStartArc
[in] Specifies the logical x-coordinate of the ending point of the radial line defining the starting point of the arc.
nYStartArc
[in] Specifies the logical y-coordinate of the ending point of the radial line defining the starting point of the arc.
nXEndArc
[in] Specifies the logical x-coordinate of the ending point of the radial line defining the ending point of the arc.
nYEndArc
[in] Specifies the logical y-coordinate of the ending point of the radial line defining the ending point of the arc.

Return Values

If the arc is drawn, the return value is nonzero.

If the arc is not drawn, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The points (nLeftRect, nTopRect) and (nRightRect, nBottomRect) specify the bounding rectangle. An ellipse formed by the specified bounding rectangle defines the curve of the arc. The arc extends in the current drawing direction from the point where it intersects the radial from the center of the bounding rectangle to the (nXStartArc, nYStartArc) point. The arc ends where it intersects the radial from the center of the bounding rectangle to the (nXEndArc, nYEndArc) point. If the starting point and ending point are the same, a complete ellipse is drawn.

The arc is drawn using the current pen; it is not filled.

The current position is neither used nor updated by Arc.

Windows 95/98: The drawing direction is always counterclockwise.

Windows NT/2000: Use the GetArcDirection and SetArcDirection functions to get and set the current drawing direction for a device context. The default drawing direction is counterclockwise.

Windows 95/98: The sum of the coordinates of the bounding rectangle cannot exceed 32,767. The sum of nLeftRect and nRightRect or nTopRect and nBottomRect parameters cannot exceed 32,767.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, AngleArc, ArcTo, Chord, Ellipse, GetArcDirection, Pie, SetArcDirection


ArcTo

The ArcTo function draws an elliptical arc.

BOOL ArcTo(
  HDC hdc,          // handle to device context
  int nLeftRect,    // x-coord of rectangle's upper-left corner
  int nTopRect,     // y-coord of rectangle's upper-left corner
  int nRightRect,   // x-coord of rectangle's lower-right corner
  int nBottomRect,  // y-coord of rectangle's lower-right corner
  int nXRadial1,    // x-coord of first radial ending point
  int nYRadial1,    // y-coord of first radial ending point
  int nXRadial2,    // x-coord of second radial ending point
  int nYRadial2     // y-coord of second radial ending point
);

Parameters

hdc
[in] Handle to the device context where drawing takes place.
nLeftRect
[in] Specifies the logical x-coordinate of the upper-left corner of the bounding rectangle.
nTopRect
[in] Specifies the logical y-coordinate of the upper-left corner of the bounding rectangle.
nRightRect
[in] Specifies the logical x-coordinate of the lower-right corner of the bounding rectangle.
nBottomRect
[in] Specifies the logical y-coordinate of the lower-right corner of the bounding rectangle.
nXRadial1
[in] Specifies the logical x-coordinate of the endpoint of the radial defining the starting point of the arc.
nYRadial1
[in] Specifies the logical y-coordinate of the endpoint of the radial defining the starting point of the arc.
nXRadial2
[in] Specifies the logical x-coordinate of the endpoint of the radial defining the ending point of the arc.
nYRadial2
[in] Specifies the logical y-coordinate of the endpoint of the radial defining the ending point of the arc.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

ArcTo is similar to the Arc function, except that the current position is updated.

The points (nLeftRect, nTopRect) and (nRightRect, nBottomRect) specify the bounding rectangle. An ellipse formed by the specified bounding rectangle defines the curve of the arc. The arc extends counterclockwise from the point where it intersects the radial line from the center of the bounding rectangle to the (nXRadial1, nYRadial1) point. The arc ends where it intersects the radial line from the center of the bounding rectangle to the (nXRadial2, nYRadial2) point. 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, AngleArc, Arc, SetArcDirection


GetArcDirection

The GetArcDirection function retrieves the current arc direction for the specified device context. Arc and rectangle functions use the arc direction.

int GetArcDirection(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context.

Return Values

The return value specifies the current arc direction; it can be any one of the following values:

Value | Meaning
AD_COUNTERCLOCKWISE | Arcs and rectangles are drawn counterclockwise.
AD_CLOCKWISE | Arcs and rectangles are drawn clockwise.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, SetArcDirection


LineDDA

The LineDDA function determines which pixels should be highlighted for a line defined by the specified starting and ending points.

BOOL LineDDA(
  int nXStart,             // x-coordinate of starting point
  int nYStart,             // y-coordinate of starting point
  int nXEnd,               // x-coordinate of ending point
  int nYEnd,               // y-coordinate of ending point
  LINEDDAPROC lpLineFunc,  // callback function
  LPARAM lpData            // application-defined data
);

Parameters

nXStart
[in] Specifies the x-coordinate of the line's starting point.
nYStart
[in] Specifies the y-coordinate of the line's starting point.
nXEnd
[in] Specifies the x-coordinate of the line's ending point.
nYEnd
[in] Specifies the y-coordinate of the line's ending point.
lpLineFunc
[in] Pointer to an application-defined callback function. For more information, see the LineDDAProc callback function.
lpData
[in] Pointer to the application-defined data.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The LineDDA function passes the coordinates for each point along the line, except for the line's ending point, to the application-defined callback function. In addition to passing the coordinates of a point, this function passes any existing application-defined data.

The coordinates passed to the callback function match pixels on a video display only if the default transformations and mapping modes are used.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, LineDDAProc


LineDDAProc

The LineDDAProc function is an application-defined callback function used with the LineDDA function. It is used to process coordinates. The LINEDDAPROC type defines a pointer to this callback function. LineDDAProc is a placeholder for the application-defined function name.

VOID CALLBACK LineDDAProc(
  int X,          // x-coordinate of point
  int Y,          // y-coordinate of point
  LPARAM lpData   // application-defined data
);

Parameters

X
[in] Specifies the x-coordinate of the current point.
Y
[in] Specifies the y-coordinate of the current point.
lpData
[in] Pointer to the application-defined data.

Return Values

This function does not return a value.

Remarks

An application registers a LineDDAProc function by passing its address to the LineDDA function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Lines and Curves Overview, Line and Curve Functions, LineDDA


LineTo

The LineTo function draws a line from the current position up to, but not including, the specified point.

BOOL LineTo(
  HDC hdc,    // device context handle
  int nXEnd,  // x-coordinate of ending point
  int nYEnd   // y-coordinate of ending point
);

Parameters

hdc
[in] Handle to a device context.
nXEnd
[in] Specifies the x-coordinate of the line's ending point.
nYEnd
[in] Specifies the y-coordinate of the line's ending point.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The coordinates of the line's ending point are specified in logical units.

The line is drawn by using the current pen and, if the pen is a geometric pen, the current brush.

If LineTo succeeds, the current position is set to the specified ending point.

For an example, see Drawing Markers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, MoveToEx, Polyline, PolylineTo


MoveToEx

The MoveToEx function updates the current position to the specified point and optionally returns the previous position.

BOOL MoveToEx(
  HDC hdc,          // handle to device context
  int X,            // x-coordinate of new current position
  int Y,            // y-coordinate of new current position
  LPPOINT lpPoint   // old current position
);

Parameters

hdc
[in] Handle to a device context.
X
[in] Specifies the x-coordinate of the new position, in logical units.
Y
[in] Specifies the y-coordinate of the new position, in logical units.
lpPoint
[out] Pointer to a POINT structure that receives the previous current position. If this parameter is a NULL pointer, the previous position is not returned.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The MoveToEx function affects all drawing functions.

For an example, see Drawing Markers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, AngleArc, LineTo, POINT, PolyBezierTo, PolylineTo


PolyBezier

The PolyBezier function draws one or more Bézier curves.

BOOL PolyBezier(
  HDC hdc,            // handle to device context
  CONST POINT* lppt,  // endpoints and control points
  DWORD cPoints       // count of endpoints and control points
);

Parameters

hdc
[in] Handle to a device context.
lppt
[in] Pointer to an array of POINT structures that contain the endpoints and control points of the curve(s).
cPoints
[in] Specifies the number of points in the lppt array. This value must be one more than three times the number of curves to be drawn, because each Bézier curve requires two control points and an endpoint, and the initial curve requires an additional starting point.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Th Polybezier function draws cubic Bézier curves by using the endpoints and control points specified by the lppt parameter. The first curve is drawn from the first point to the fourth point by using the second and third points as control points. Each subsequent curve in the sequence needs exactly three more points: the ending point of the previous curve is used as the starting point, the next two points in the sequence are control points, and the third is the ending 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.

Windows 95/98: PolyBezier cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum points allowed
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but device does not support wideline | approximately 1360 (that is, approximately 16K / 12)

Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments.

For an example, see Redrawing in the Update Region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, MoveToEx, POINT, PolyBezierTo


PolyBezierTo

The PolyBezierTo function draws one or more Bézier curves.

BOOL PolyBezierTo(
  HDC hdc,            // handle to device context
  CONST POINT *lppt,  // endpoints and control points
  DWORD cCount        // count of endpoints and control points
);

Parameters

hdc
[in] Handle to a device context.
lppt
[in] Pointer to an array of POINT structures that contains the endpoints and control points.
cCount
[in] Specifies the number of points in the lppt array. This value must be three times the number of curves to be drawn, because each Bézier curve requires two control points and an ending point.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

This function draws cubic Bézier curves by using the control points specified by the lppt parameter. The first curve is drawn from the current position to the third point by using the first two points as control points. For each subsequent curve, the function needs exactly three more points, and uses the ending point of the previous curve as the starting point for the next.

PolyBezierTo moves the current position to the ending point of the last Bézier curve. The figure is not filled.

This function draws lines by using the current pen.

Windows 95/98: PolyBezierTo cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum points allowed
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but device does not support wideline | approximately 1360 (that is, approximately 16K / 12)

Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, MoveToEx, POINT, PolyBezier


PolyDraw

The PolyDraw function draws a set of line segments and Bézier curves.

BOOL PolyDraw(
  HDC hdc,               // handle to device context
  CONST POINT *lppt,     // array of points
  CONST BYTE *lpbTypes,  // line and curve identifiers
  int cCount             // count of points
);

Parameters

hdc
[in] Handle to a device context.
lppt
[in] Pointer to an array of POINT structures that contains the endpoints for each line segment and the endpoints and control points for each Bézier curve.
lpbTypes
[in] Pointer to an array that specifies how each point in the lppt array is used. This parameter can be one of the following values.
Type | Meaning
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 Bézier curve.

PT_BEZIERTO types always occur in sets of three. The current position defines the starting point for the Bézier curve. 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 value by using the bitwise operator OR to indicate that the corresponding point is the last point in a figure and the figure is closed.
Value Meaning
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 MoveToEx point.

This value is combined with the PT_LINETO type for a line, or with the PT_BEZIERTO type of the ending point for a Bézier curve, by using the bitwise operator OR.

The current position is set to the ending point of the closing line.

cCount
[in] Specifies the total number of points in the lppt array, the same as the number of bytes in the lpbTypes array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The PolyDraw function can be used in place of consecutive calls to MoveToEx, LineTo, and PolyBezierTo functions to draw disjoint figures. The lines and curves are drawn using the current pen and figures are not filled. If there is an active path started by calling BeginPath, PolyDraw adds to the path.

The points contained in the lppt array and in the lpbTypes array indicate whether each point is part of a MoveTo, LineTo, or PolyBezierTo operation. It is also possible to close figures.

This function updates the current position.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, BeginPath, EndPath, LineTo, MoveToEx, POINT, PolyBezierTo, PolyLine


Polyline

The Polyline function draws a series of line segments by connecting the points in the specified array.

BOOL Polyline(
  HDC hdc,            // handle to device context
  CONST POINT *lppt,  // array of endpoints
  int cPoints         // number of points in array
);

Parameters

hdc
[in] Handle to a device context.
lppt
[in] Pointer to an array of POINT structures. Each structure in the array identifies a point in logical space.
cPoints
[in] Specifies the number of points in the array. This number must be greater than or equal to two.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The lines are drawn from the first point through subsequent points by using the current pen. Unlike the LineTo or PolylineTo functions, the Polyline function neither uses nor updates the current position.

Windows 95/98: Polyline cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum points allowed
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but device does not support wideline | approximately 1360 (that is, approximately 16K / 12)

Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, LineTo, MoveToEx, POINT, PolylineTo, PolyPolyline


PolylineTo

The PolylineTo function draws one or more straight lines.

BOOL PolylineTo(
  HDC hdc,            // handle to device context
  CONST POINT *lppt,  // array of points
  DWORD cCount        // number of points in array
);

Parameters

hdc
[in] Handle to the device context.
lppt
[in] Pointer to an array of POINT structures that contains the vertices of the line.
cCount
[in] Specifies the number of points in the array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Unlike the Polyline function, the PolylineTo function uses and updates the current position.

A line is drawn from the current position to the first point specified by the lppt 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 lppt.

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.

Windows 95/98: PolylineTo cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum points allowed
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but device does not support wideline | approximately 1360 (that is, approximately 16K / 12)

Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, LineTo, MoveToEx, POINT, Polyline, PolyPolyline


PolyPolyline

The PolyPolyline function draws multiple series of connected line segments.

BOOL PolyPolyline(
  HDC hdc,                      // handle to device context
  CONST POINT *lppt,            // array of points
  CONST DWORD *lpdwPolyPoints,  // array of values
  DWORD cCount                  // number of entries in values array
);

Parameters

hdc
[in] Handle to the device context.
lppt
[in] Pointer to an array of POINT structures that contains the vertices of the polylines. The polylines are specified consecutively.
lpdwPolyPoints
[in] Pointer to an array of variables specifying the number of points in the lppt array for the corresponding polyline. Each entry must be greater than or equal to two.
cCount
[in] Specifies the total number of entries in the lpdwPolyPoints array.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

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.

Windows 95/98: PolyPolyline cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table.

Line width | Maximum points allowed
line width is 1 | 16K
line width > 1 (that is, wideline) and device supports wideline | 16K
line width > 1 but device does not support wideline | approximately 1360 (that is, approximately 16K / 12)

Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions, POINT, Polyline, PolylineTo


SetArcDirection

The SetArcDirection sets the drawing direction to be used for arc and rectangle functions.

int SetArcDirection(
  HDC hdc,           // handle to device context
  int ArcDirection   // new arc direction
);

Parameters

hdc
[in] Handle to the device context.
ArcDirection
[in] Specifies the new arc direction. This parameter can be one of the following values.
Value | Meaning
AD_COUNTERCLOCKWISE | Figures drawn counterclockwise.
AD_CLOCKWISE | Figures drawn clockwise.

Return Values

If the function succeeds, the return value specifies the old arc direction.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The default direction is counterclockwise.

The SetArcDirection function specifies the direction in which the following functions draw:

Arc
ArcTo
Chord
Ellipse
Pie
Rectangle
RoundRect

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Lines and Curves Overview, Line and Curve Functions


Metafiles

A metafile is a collection of structures that store a picture in a device-independent format. Device independence is the one feature that sets metafiles apart from bitmaps. Unlike a bitmap, a metafile guarantees device independence. There is a drawback to metafiles however, they are generally drawn more slowly than bitmaps. Therefore, if an application requires fast drawing and device independence is not an issue, it should use bitmaps instead of metafiles.

  • About Metafiles
  • Using Metafiles
  • Metafile Reference

For information about bitmaps, see Bitmaps.


About Metafiles

Internally, a metafile is an array of variable-length structures called metafile records. The first records in the metafile specify general information such as the resolution of the device on which the picture was created, the dimensions of the picture, and so on. The remaining records, which constitute the bulk of any metafile, correspond to the graphics device interface (GDI) functions required to draw the picture. These records are stored in the metafile after a special metafile device context is created. This metafile device context is then used for all drawing operations required to create the picture. When the system processes a GDI function associated with a metafile DC, it converts the function into the appropriate data and stores this data in a record appended to the metafile.

After a picture is complete and the last record is stored in the metafile, you can pass the metafile to another application by:

  • Using the clipboard
  • Embedding it within another file
  • Storing it on disk
  • Playing it repeatedly

A metafile is played when its records are converted to device commands and processed by the appropriate device.

There are two types of metafiles:

  • Enhanced-format metafiles
  • Windows-format metafiles


Enhanced-Format Metafiles

An enhanced-format metafile is used by Win32®-based applications. The enhanced format consists of the following elements:

  • A header
  • A table of handles to GDI objects
  • A private palette
  • An array of metafile records

Enhanced metafiles provide true device independence. You can think of the picture stored in an enhanced metafile as a "snapshot" of the video display taken at a particular moment. This "snapshot" maintains its dimensions no matter where it appears—on a printer, a plotter, the desktop, or in the client area of any Win32-based application.

You can use enhanced metafiles to store a picture created by using the Win32 GDI functions (including new path and transformation functions). Because the enhanced metafile format is standardized, pictures that are stored in this format can be copied from one Win32-based application to another; and, because the pictures are truly device independent, they are guaranteed to maintain their shape and proportion on any output device.


Enhanced Metafile Records

An enhanced metafile is an array of records. A metafile record is a variable-length ENHMETARECORD structure. At the beginning of every enhanced metafile record is an EMR structure, which contains two members. The first member, iType, identifies the record type — that is, the GDI function whose parameters are contained in the record. Because the structures are variable in length, the other member, nSize, contains the size of the record. Immediately following the nSize member are the remaining parameters, if any, of the GDI function. The remainder of the structure contains additional data that is dependent on the record type.

The first record in an enhanced metafile is always the ENHMETAHEADER structure, which is the enhanced-metafile header. The header specifies the following information:

  • Size of the metafile, in bytes
  • Dimensions of the picture frame, in device units
  • Dimensions of the picture frame, in .01-millimeter units
  • Number of records in the metafile
  • Offset to an optional text description
  • Size of the optional palette
  • Resolution of the original device, in pixels
  • Resolution of the original device, in millimeters

An optional text description can follow the header record. The text description describes the picture and the author's name. The optional palette specifies the colors used to create the enhanced metafile. The remaining records identify the GDI functions used to create the picture. The following hexadecimal output corresponds to a record generated for a call to the SetMapMode function.

00000011 0000000C 00000004

The value 0x00000011 specifies the record type (corresponds to the EMR_SETMAPMODE constant defined in the file Wingdi.h). The value 0x0000000C specifies the length of the record, in bytes. The value 0x00000004 identifies the mapping mode (corresponds to the MM_LOENGLISH constant defined in the SetMapMode function).

For a list of additional record types, see Metafile Structures.


Enhanced Metafile Creation

You create an enhanced metafile by using the CreateEnhMetaFile function, supplying the appropriate arguments. The system uses these arguments to maintain picture dimensions, determine whether the metafile should be stored on a disk or in memory, and so on.

To maintain picture dimensions across output devices, CreateEnhMetaFile requires the resolution of the reference device. This reference device is the device on which the picture first appeared, and the reference DC is the device context associated with the reference device. When calling the CreateEnhMetaFile function, you must supply a handle that identifies this DC. You can get this handle by calling the GetDC or CreateDC function. You can also specify NULL as the handle to use the current display device for the reference device.

Most applications store pictures permanently and therefore create an enhanced metafile that is stored on a disk; however, there are some instances when this is not necessary. For example, a word-processing application that provides chart-drawing capabilities could store a user-defined chart in memory as an enhanced metafile and then copy the enhanced metafile bits from memory into the user's document file. An application that requires a metafile that is stored permanently on a disk must supply the file name when it calls CreateEnhMetaFile. If you do not supply a file name, the system automatically treats the metafile as a temporary file and stores it in memory.

You can add an optional text description to a metafile containing information about the picture and the author. An application can display these strings in the File Open dialog box to provide the user with information about metafile content that will help in selecting the appropriate file. If an application includes the text description, it must supply a pointer to the string when it calls CreateEnhMetaFile.

When CreateEnhMetaFile succeeds, it returns a handle that identifies a special metafile device context. A metafile device context is unique in that it is associated with a file rather than with an output device. When the system processes a GDI function that received a handle to a metafile device context, it converts the GDI function into an enhanced-metafile record and appends the record to the end of the enhanced metafile.

After a picture is complete and the last record is appended to the enhanced metafile, the application can close the file by calling the CloseEnhMetaFile function. This function closes and deletes the special metafile device context and returns a handle identifying the enhanced metafile.

To delete an enhanced-format metafile or an enhanced-format metafile handle, call the DeleteEnhMetaFile function.


Enhanced Metafile Operations

You can use the handle to an enhanced metafile to accomplish the following tasks:

  • Display the picture stored in an enhanced metafile.
  • Create copies of an enhanced metafile.
  • Edit an enhanced metafile.
  • Retrieve the optional description stored in an enhanced metafile.
  • Retrieve a copy of an enhanced-metafile header.
  • Retrieve a binary version of an enhanced metafile.
  • Enumerate the colors in the optional palette.

These tasks are discussed in the sections in the remainder of this topic.

Display the Picture Stored in an Enhanced Metafile

You can display the picture stored in an enhanced metafile using the PlayEnhMetaFile function. Pass the function a handle to the enhanced metafile, without being concerned with the format of the enhanced metafile records. However, it is sometimes desirable to enumerate the records in the enhanced metafile to search for a particular GDI function and modify the parameters of the function in some manner. To do this, you can use EnumEnhMetaFile and provide a callback function, EnhMetaFileProc, to process the enhanced metafile records. To modify the parameters for an enhanced metafile record, you must know the format of the parameters within the record.

Create Copies of an Enhanced Metafile

Some applications create temporary backup (or duplicate) copies of a file before enabling the user to alter the original. An application can create a backup copy of an enhanced metafile by calling the CopyEnhMetaFile function, supplying a handle that identifies the enhanced metafile, and supplying a pointer to the name of the new file.

To create a memory-based enhanced-format metafile, call the SetEnhMetaFileBits function.

Edit an Enhanced Metafile

Most drawing, illustration, and computer-aided design (CAD) applications require a means of editing a picture stored in an enhanced metafile. Although editing an enhanced metafile is a complex task, you can use the EnumEnhMetaFile function in combination with other functions to provide this capability in your application. The EnumEnhMetaFile function and its associated callback function, EnhMetaFileProc, enable the application to process individual records in an enhanced metafile.

Retrieve the Optional Description Stored in an Enhanced Metafile

Some applications display the text description of an enhanced metafile with the corresponding file name in the Open dialog box. You can determine whether this string exists in an enhanced metafile by retrieving the metafile header with the GetEnhMetaFileHeader function and examining one of its members. If the string exists, the application retrieves it by calling the GetEnhMetaFileDescription function.

Retrieve a Binary Version of an Enhanced Metafile

You can retrieve the contents of a metafile by calling the GetEnhMetaFileBits function; however, before retrieving the contents, you must specify the size of the file. To get the size, you can use the GetEnhMetaFileHeader function and examine the appropriate member.

Enumerate the Colors in the Optional Palette

To achieve consistent colors when a picture is displayed on various output devices, you can call the CreatePalette function and store a logical palette in an enhanced metafile. An application that displays the picture stored in the enhanced metafile retrieves this palette and calls the RealizePalette function before displaying the picture. To determine whether a palette is stored in an enhanced metafile, retrieve the metafile header and examine the appropriate member. If a palette exists, you can call the GetEnhMetaFilePaletteEntries function to retrieve the logical palette.


Windows-Format Metafiles

Microsoft® Windows®-format metafiles are limited in their capabilities and should rarely be used — the Windows-format functions are supported to maintain backward compatibility with applications that were written to run as 16 bit Windows-based applications. Instead, you should use the enhanced-format functions.

A Windows-format metafile is used by 16-bit Windows-based applications. The format consists of a header and an array of metafile records.

The following are the limitations of this format:

  • A Windows-format metafile is application and device dependent. Changes in the application's mapping modes or the device resolution affect the appearance of metafiles created in this format.
  • A Windows-format metafile does not contain a comprehensive header that describes the original picture dimensions, the resolution of the device on which the picture was created, an optional text description, or an optional palette.
  • A Windows-format metafile does not support the new curve, path, and transformation functions. See the list of supported functions in the table that follows.
  • Some Windows-format metafile records cannot be scaled.
  • The metafile device context associated with a Windows-format metafile cannot be queried (that is, an application cannot retrieve device-resolution data, font metrics, and so on).

The following are the only functions that are supported in Windows-format metafiles.

AnimatePalette

Arc

BitBlt

Chord

CreateBrushIndirect

CreateDIBPatternBrush

CreateFontIndirect

CreatePalette

CreatePatternBrush

CreatePenIndirect

DeleteObject

Ellipse

Escape

ExcludeClipRect

ExtFloodFill

ExtTextOut

FillRgn

FloodFill

FrameRgn

IntersectClipRect

InvertRgn

 LineTo

MoveToEx

OffsetClipRgn

OffsetViewportOrgEx

OffsetWindowOrgEx

PaintRgn

PatBlt

Pie

Polygon

Polyline

PolyPolygon

RealizePalette

Rectangle

ResizePalette

RestoreDC

RoundRect

SaveDC

ScaleViewportExtEx

ScaleWindowExtEx

SelectClipRgn

SelectObject

 SelectPalette

SetBkColor

SetBkMode

SetDIBitsToDevice

SetMapMode

SetMapperFlags

SetPaletteEntries

SetPixel

SetPolyFillMode

SetROP2

SetStretchBltMode

SetTextAlign

SetTextCharacterExtra

SetTextColor

SetTextJustification

SetViewportOrgEx

SetWindowExtEx

SetWindowOrgEx

StretchBlt

StretchDIBits

TextOut

To convert a Windows-format metafile to an enhanced-format metafile, call the GetMetaFileBitsEx function to retrieve the data from the Windows-format metafile and then call the SetWinMetaFileBits function to convert this data into an enhanced-format metafile. To convert an enhanced-format record into a Windows-format record, call the GetWinMetaFileBits function.


Using Metafiles

This section explains how to perform the following tasks:

  • Creating an enhanced metafile
  • Displaying a picture and storing it in an enhanced metafile
  • Opening an enhanced metafile and displaying its contents
  • Editing an enhanced metafile


Creating an Enhanced Metafile

This section contains an example that demonstrates the creation of an enhanced metafile that is stored on a disk, using a file name specified by the user.

The example uses a device context for the application window as the reference device context. (The system stores the resolution data for this device in the enhanced-metafile's header.) The application retrieves a handle identifying this device context by calling the GetDC function.

The example uses the dimensions of the application's client area to define the dimensions of the picture frame. Using the rectangle dimensions returned by the GetClientRect function, the application converts the device units to .01-millimeter units and passes the converted values to the CreateEnhMetaFile function.

The example displays a Save As common dialog box that enables the user to specify the file name of the new enhanced metafile. The system appends the three-character .emf extension to this file name and passes the name to the CreateEnhMetaFile function.

The example also embeds a text description of the picture in the enhanced-metafile header. This description is specified as a resource in the string table of the application's resource file. However, in a working application, this string would be retrieved from a custom control in a common dialog box or from a separate dialog box displayed solely for this purpose.

// Obtain a handle to a reference device context.

hdcRef = GetDC(hWnd);

// Determine the picture frame dimensions.
// iWidthMM is the display width in millimeters.
// iHeightMM is the display height in millimeters.
// iWidthPels is the display width in pixels.
// iHeightPels is the display height in pixels

iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE);
iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE);
iWidthPels = GetDeviceCaps(hdcRef, HORZRES);
iHeightPels = GetDeviceCaps(hdcRef, VERTRES);

// Retrieve the coordinates of the client
// rectangle, in pixels.

GetClientRect(hWnd, &rect);

// Convert client coordinates to .01-mm units.
// Use iWidthMM, iWidthPels, iHeightMM, and
// iHeightPels to determine the number of
// .01-millimeter units per pixel in the x-
//  and y-directions.

rect.left = (rect.left * iWidthMM * 100)/iWidthPels;
rect.top = (rect.top * iHeightMM * 100)/iHeightPels;
rect.right = (rect.right * iiWidthMM * 100)/iWidthPels;
rect.bottom = (rect.bottom * iHeightMM * 100)/iHeightPels;

// Load the filename filter from the string table.

LoadString(hInst, IDS_FILTERSTRING,
     (LPSTR)szFilter, sizeof(szFilter));

// Replace the '%' separators that are embedded
// between the strings in the string-table entry
// with '\0'.

for (i=0; szFilter[i]!='\0'; i++)
    if (szFilter[i] == '%')
            szFilter[i] = '\0';

// Load the dialog title string from the table.

LoadString(hInst, IDS_TITLESTRING,
     (LPSTR)szTitle, sizeof(szTitle));

// Initialize the OPENFILENAME members.

szFile[0] = '\0';

Ofn.lStructSize = sizeof(OPENFILENAME);
Ofn.hwndOwner = hWnd;
Ofn.lpstrFilter = szFilter;
Ofn.lpstrFile= szFile;
Ofn.nMaxFile = sizeof(szFile);
Ofn.lpstrFileTitle = szFileTitle;
Ofn.nMaxFileTitle = sizeof(szFileTitle);
Ofn.lpstrInitialDir = (LPSTR)NULL;
Ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT;
Ofn.lpstrTitle = szTitle;

// Display the Filename common dialog box. The
// filename specified by the user is passed
// to the CreateEnhMetaFile function and used to
// store the metafile on disk.

GetSaveFileName(&Ofn);

// Load the description from the string table.

LoadString(hInst, IDS_DESCRIPTIONSTRING,
     (LPSTR)szDescription, sizeof(szDescription));

// Replace the '%' string separators that are
// embedded between strings in the string-table
// entry with '\0'.

for (i=0; szDescription[i]!='\0'; i++)
{
    if (szDescription[i] == '%')
            szDescription[i] = '\0';
}

// Create the metafile device context.

hdcMeta = CreateEnhMetaFile(hdcRef,
          (LPTSTR) Ofn.lpstrFile,
          &rect, (LPSTR)szDescription);

if (!hdcMeta)
    errhandler("CreateEnhMetaFile", hWnd);

// Release the reference device context.

ReleaseDC(hWnd, hdcRef);


Displaying a Picture and Storing It in an Enhanced Metafile

This section contains an example demonstrating the creation of a picture and the process of storing the corresponding records in a metafile. The example draws a picture to the display or stores it in a metafile. If a display device context handle is given, it draws a picture to the screen using various GDI functions. If an enhanced metafile device context is given, it stores the same picture in the enhanced metafile.

void DrawOrStore(HWND hwnd, HDC hdcMeta, HDC hdcDisplay)
{

RECT rect;
HDC hDC;
int fnMapModeOld;
HBRUSH hbrOld;

// Draw it to the display DC or store it in the metafile device context.

if (hdcMeta)
    hDC = hdcMeta;
else
    hDC = hdcDisplay;

// Set the mapping mode in the device context.

fnMapModeOld = SetMapMode(hDC, MM_LOENGLISH);

// Find the midpoint of the client area.

GetClientRect(hwnd, (LPRECT)&rect);
DPtoLP(hDC, (LPPOINT)&rect, 2);

// Select a gray brush.

hbrOld = SelectObject(hDC, GetStockObject(GRAY_BRUSH));

// Draw a circle with a one inch raduis.

Ellipse(hDC, (rect.right/2 - 100), (rect.bottom/2 + 100),
       (rect.right/2 + 100), (rect.bottom/2 - 100));

// Perform additional drawing here.

// Set the device context back to its original state.

SetMapMode(hDC, fnMapModeOld);
SelectObject(hDC, hbrOld);
}


Opening an Enhanced Metafile and Displaying Its Contents

This section contains an example demonstrating how an application opens an enhanced metafile stored on disk and displays the associated picture in the client area.

The example uses the Open common dialog box to enable the user to select an enhanced metafile from a list of existing files. It then passes the name of the selected file to the GetEnhMetaFile function, which returns a handle identifying the file. This handle is passed to the PlayEnhMetaFile function in order to display the picture.

LoadString(hInst, IDS_FILTERSTRING,
     (LPSTR)szFilter, sizeof(szFilter));

// Replace occurrences of '%' string separator
// with '\0'.

for (i=0; szFilter[i]!='\0'; i++)
{
    if (szFilter[i] == '%')
            szFilter[i] = '\0';
}

LoadString(hInst, IDS_DEFEXTSTRING,
     (LPSTR)szDefExt, sizeof(szFilter));

// Use the OpenFilename common dialog box
// to obtain the desired filename.

szFile[0] = '\0';
Ofn.lStructSize = sizeof(OPENFILENAME);
Ofn.hwndOwner = hWnd;
Ofn.lpstrFilter = szFilter;
Ofn.lpstrCustomFilter = (LPSTR)NULL;
Ofn.nMaxCustFilter = 0L;
Ofn.nFilterIndex = 1L;
Ofn.lpstrFile = szFile;
Ofn.nMaxFile = sizeof(szFile);
Ofn.lpstrFileTitle = szFileTitle;
Ofn.nMaxFileTitle = sizeof(szFileTitle);
Ofn.lpstrInitialDir = (LPSTR) NULL;
Ofn.lpstrTitle = (LPSTR)NULL;
Ofn.Flags = OFN_SHOWHELP | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
Ofn.nFileOffset = 0;
Ofn.nFileExtension = 0;
Ofn.lpstrDefExt = szDefExt;

GetOpenFileName(&Ofn);

// Open the metafile.

hemf = GetEnhMetaFile(Ofn.lpstrFile);

// Retrieve a handle to a window device context.

hDC = GetDC(hWnd);

// Retrieve the client rectangle dimensions.

GetClientRect(hWnd, &rct);

// Draw the picture.

PlayEnhMetaFile(hDC, hemf, &rct);

// Release the metafile handle.

DeleteEnhMetaFile(hemf);

// Release the window DC.

ReleaseDC(hWnd, hDC);


Editing an Enhanced Metafile

To edit a picture stored in an enhanced metafile, an application must perform the tasks described in the following procedure.

To edit a picture stored in an enhanced metafile

  1. Use hit-testing to capture the cursor coordinates and retrieve the position of the object (line, arc, rectangle, ellipse, polygon, or irregular shape) that the user wants to alter.
  2. Convert these coordinates to logical (or world) units.
  3. Call the EnumEnhMetaFile function and examine each metafile record.
  4. Determine whether a given record corresponds to a GDI drawing function.
  5. If it does, determine whether the coordinates stored in the record correspond to the line, arc, ellipse, or other graphics element that intersects the coordinates specified by the user.
  6. Upon finding the record that corresponds to the output that the user wants to alter, erase the object on the screen that corresponds to the original record.
  7. Delete the corresponding record from the metafile, saving a pointer to its location.
  8. Permit the user to redraw or replace the object.
  9. Convert the GDI functions used to draw the new object into one or more enhanced-metafile records.
  10. Store these records in the enhanced metafile.


Metafile Reference

The following elements are used with metafiles:

  • Metafile Functions
  • Metafile Structures


Metafile Functions

The following functions are used with enhanced-format metafiles.

Function | Description
CloseEnhMetaFile | Closes an enhanced-metafile device context.
CopyEnhMetaFile | Copies the contents of an enhanced-format metafile to a specified file.
CreateEnhMetaFile | Creates a device context for an enhanced-format metafile.
DeleteEnhMetaFile | Deletes an enhanced-format metafile or an enhanced-format metafile handle.
EnhMetaFileProc | An application-defined callback function used with the EnumEnhMetaFile function.
EnumEnhMetaFile | Enumerates the records within an enhanced-format metafile.
GdiComment | Copies a comment from a buffer into a specified enhanced-format metafile.
GetEnhMetaFile | Creates a handle that identifies the enhanced-format metafile stored in the specified file.
GetEnhMetaFileBits | Retrieves the contents of the specified enhanced-format metafile and copies them into a buffer.
GetEnhMetaFileDescription | Retrieves an optional text description from an enhanced-format metafile and copies the string to the specified buffer.
GetEnhMetaFileHeader | Retrieves the record containing the header for the specified enhanced-format metafile.
GetEnhMetaFilePaletteEntries | Retrieves optional palette entries from the specified enhanced metafile.
GetWinMetaFileBits | Converts the enhanced-format records from a metafile into Windows-format records.
PlayEnhMetaFile | Displays the picture stored in the specified enhanced-format metafile.
PlayEnhMetaFileRecord | Plays an enhanced-metafile record by executing the graphics device interface (GDI) functions identified by the record.
SetEnhMetaFileBits | Creates a memory-based enhanced-format metafile from the specified data.
SetWinMetaFileBits | Converts a metafile from the older Windows format to the new enhanced format.

Obsolete Functions

The following functions are obsolete. The are provided for compatibility with Windows-format metafiles.

CloseMetaFile
CopyMetaFile
CreateMetaFile
DeleteMetaFile
EnumMetaFile
EnumMetaFileProc
GetMetaFileBitsEx
PlayMetaFile
PlayMetaFileRecord
SetMetaFileBitsEx


CloseEnhMetaFile

The CloseEnhMetaFile function closes an enhanced-metafile device context and returns a handle that identifies an enhanced-format metafile.

HENHMETAFILE CloseEnhMetaFile(
  HDC hdc   // handle to enhanced-metafile DC
);

Parameters

hdc
[in] Handle to an enhanced-metafile device context.

Return Values

If the function succeeds, the return value is a handle to an enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can use the enhanced-metafile handle returned by the CloseEnhMetaFile function to perform the following tasks:

  • Display a picture stored in an enhanced metafile
  • Create copies of the enhanced metafile
  • Enumerate, edit, or copy individual records in the enhanced metafile
  • Retrieve an optional description of the metafile contents from the enhanced-metafile header
  • Retrieve a copy of the enhanced-metafile header
  • Retrieve a binary copy of the enhanced metafile
  • Enumerate the colors in the optional palette
  • Convert an enhanced-format metafile into a Windows-format metafile

When the application no longer needs the enhanced metafile handle, it should release the handle by calling the DeleteEnhMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CopyEnhMetaFile, CreateEnhMetaFile, DeleteEnhMetaFile, EnumEnhMetaFile, GetEnhMetaFileBits, GetWinMetaFileBits, PlayEnhMetaFile


CloseMetaFile

The CloseMetaFile function closes a metafile device context and returns a handle that identifies a Windows-format metafile.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the CloseEnhMetaFile function.

HMETAFILE CloseMetaFile(
  HDC hdc   // handle to Windows-metafile DC
);

Parameters

hdc
[in] Handle to a metafile device context used to create a Windows-format metafile.

Return Values

If the function succeeds, the return value is a handle to a Windows-format metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should call the enhanced-format metafile functions.

To convert a Windows-format metafile into a new enhanced-format metafile, use the SetWinMetaFileBits function.

When an application no longer needs the Windows-format metafile handle, it should delete the handle by calling the DeleteMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, CloseEnhMetaFile, CopyMetaFile, CreateMetaFile, DeleteMetaFile, EnumMetaFile, GetMetaFileBitsEx, PlayMetaFile, PolyBezier, SetWinMetaFileBits, SetWorldTransform


CopyEnhMetaFile

The CopyEnhMetaFile function copies the contents of an enhanced-format metafile to a specified file.

HENHMETAFILE CopyEnhMetaFile(
  HENHMETAFILE hemfSrc,  // handle to enhanced metafile
  LPCTSTR lpszFile       // file name
);

Parameters

hemfSrc
[in] Handle to the enhanced metafile to be copied.
lpszFile
[in] Pointer to the name of the destination file. If this parameter is NULL, the source metafile is copied to memory.

Return Values

If the function succeeds, the return value is a handle to the copy of the enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Where text arguments must use Unicode characters, use the CopyEnhMetaFile function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

Applications can use metafiles stored in memory for temporary operations.

When the application no longer needs the enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile


CopyMetaFile

The CopyMetaFile function copies the content of a Windows-format metafile to the specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the CopyEnhMetaFile function.

HMETAFILE CopyMetaFile(
  HMETAFILE hmfSrc,  // handle to Windows-format metafile
  LPCTSTR lpszFile   // file name
);

Parameters

hmfSrc
[in] Handle to the source Windows-format metafile.
lpszFile
[in] Pointer to the name of the destination file. If this parameter is NULL, the source metafile is copied to memory.

Return Values

If the function succeeds, the return value is a handle to the copy of the Windows-format metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The CopyMetaFile function supports only 16-bit Windows-based applications. It does not record or play back the new graphics device interface functions, such as PolyBezier.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

When the application no longer needs the Windows-format metafile handle, it should delete the handle by calling the DeleteMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, DeleteMetaFile


CreateEnhMetaFile

The CreateEnhMetaFile function creates a device context for an enhanced-format metafile. This device context can be used to store a device-independent picture.

HDC CreateEnhMetaFile(
  HDC hdcRef,            // handle to reference DC
  LPCTSTR lpFilename,    // file name
  CONST RECT* lpRect,    // bounding rectangle
  LPCTSTR lpDescription  // description string
);

Parameters

hdcRef
[in] Handle to a reference device for the enhanced metafile.
lpFilename
[in] Pointer to the file name for the enhanced metafile to be created. If this parameter is NULL, the enhanced metafile is memory based and its contents are lost when it is deleted by using the DeleteEnhMetaFile function.
lpRect
[in] Pointer to a RECT structure that specifies the dimensions (in .01-millimeter units) of the picture to be stored in the enhanced metafile.
lpDescription
[in] Pointer to a string that specifies the name of the application that created the picture, as well as the picture's title.

Return Values

If the function succeeds, the return value is a handle to the device context for the enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Where text arguments must use Unicode characters, use the CreateEnhMetaFile function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

The system uses the reference device identified by the hdcRef parameter to record the resolution and units of the device on which a picture originally appeared. If the hdcRef parameter is NULL, it uses the current display device for reference.

The left and top members of the RECT structure pointed to by the lpRect parameter must be less than the right and bottom members, respectively. Points along the edges of the rectangle are included in the picture. If lpRect is NULL, the graphics device interface (GDI) computes the dimensions of the smallest rectangle that surrounds the picture drawn by the application. The lpRect parameter should be provided where possible.

The string pointed to by the lpDescription parameter must contain a null character between the application name and the picture name and must terminate with two null characters—for example, "XYZ Graphics Editor\0Bald Eagle\0\0", where \0 represents the null character. If lpDescription is NULL, there is no corresponding entry in the enhanced-metafile header.

Applications use the device context created by this function to store a graphics picture in an enhanced metafile. The handle identifying this device context can be passed to any GDI function.

After an application stores a picture in an enhanced metafile, it can display the picture on any output device by calling the PlayEnhMetaFile function. When displaying the picture, the system uses the rectangle pointed to by the lpRect parameter and the resolution data from the reference device to position and scale the picture.

The device context returned by this function contains the same default attributes associated with any new device context.

Applications must use the GetWinMetaFileBits function to convert an enhanced metafile to the older Windows metafile format.

The file name for the enhanced metafile should use the .emf extension.

For an example, see Creating an Enhanced Metafile.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Metafiles Overview, Metafile Functions, CloseEnhMetaFile, DeleteEnhMetaFile, GetEnhMetaFileDescription, GetEnhMetaFileHeader, GetWinMetaFileBits, PlayEnhMetaFile, RECT


CreateMetaFile

The CreateMetaFile function creates a device context for a Windows-format metafile.

Note This function is provided only for compatibility with earlier 16-bit versions of Windows. Win32-based applications should use the CreateEnhMetaFile function.

HDC CreateMetaFile(
  LPCTSTR lpszFile   // file name
);

Parameters

lpszFile
[in] Pointer to the file name for the Windows-format metafile to be created. If this parameter is NULL, the Windows-format metafile is memory based and its contents are lost when it is deleted by using the DeleteMetaFile function.

Return Values

If the function succeeds, the return value is a handle to the device context for the Windows-format metafile.

If the function fails, the return value is NULL.

Remarks

Where text arguments must use Unicode characters, use the CreateMetaFile function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

CreateMetaFile is a Windows-format metafile function. This function supports only 16-bit Windows-based applications, which are listed in Windows-Format Metafiles. It does not record or play back the new Win32 graphics device interface (GDI) functions such as PolyBezier.

The device context created by this function can be used to record GDI output functions in a Windows-format metafile. It cannot be used with GDI query functions such as GetTextColor. When the device context is used with a GDI output function, the return value of that function becomes TRUE if the function is recorded and FALSE otherwise. When an object is selected by using the SelectObject function, only a copy of the object is recorded. The object still belongs to the application.

To create a scalable Windows-format metafile, record the graphics output in the MM_ANISOTROPIC mapping mode. The file cannot contain functions that modify the viewport origin and extents, nor can it contain device-dependent functions such as the SelectClipRgn function. Once created, the Windows metafile can be scaled and rendered to any output device-format by defining the viewport origin and extents of the picture before playing it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CloseMetaFile, CreateEnhMetaFile, DeleteMetaFile, GetTextColor, PolyBezier, SelectClipRgn, SelectObject


DeleteEnhMetaFile

The DeleteEnhMetaFile function deletes an enhanced-format metafile or an enhanced-format metafile handle.

BOOL DeleteEnhMetaFile(
  HENHMETAFILE hemf   // handle to an enhanced metafile
);

Parameters

hemf
[in] Handle to an enhanced metafile.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If the hemf parameter identifies an enhanced metafile stored in memory, the DeleteEnhMetaFile function deletes the metafile. If hemf identifies a metafile stored on a disk, the function deletes the metafile handle but does not destroy the actual metafile. An application can retrieve the file by calling the GetEnhMetaFile function.

For an example, see Opening an Enhanced Metafile and Displaying Its Contents.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CopyEnhMetaFile, CreateEnhMetaFile, GetEnhMetaFile


DeleteMetaFile

The DeleteMetaFile function deletes a Windows-format metafile or Windows-format metafile handle.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the DeleteEnhMetaFile function.

BOOL DeleteMetaFile(
  HMETAFILE hmf   // handle to Windows-format metafile
);

Parameters

hmf
[in] Handle to a Windows-format metafile.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced format metafile functions.

If the metafile identified by the hmf parameter is stored in memory (rather than on a disk), its content is lost when it is deleted by using the DeleteMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, CopyMetaFile, CreateMetaFile, DeleteEnhMetaFile, PolyBezier, SetWorldTransform


EnhMetaFileProc

The EnhMetaFileProc function is an application-defined callback function used with the EnumEnhMetaFile function. The ENHMFENUMPROC type defines a pointer to this callback function. EnhMetaFileProc is a placeholder for the application-defined function name.

int CALLBACK EnhMetaFileProc(
  HDC hDC,                      // handle to DC
  HANDLETABLE *lpHTable,        // metafile handle table
  CONST ENHMETARECORD *lpEMFR,  // metafile record
  int nObj,                     // count of objects
  LPARAM lpData                 // optional data
);

Parameters

hDC
[in] Handle to the device context passed to EnumEnhMetaFile.
lpHTable
[in] Pointer to a HANDLETABLE structure representing the table of handles associated with the graphics objects (pens, brushes, and so on) in the metafile. The first entry contains the enhanced-metafile handle.
lpEMFR
[in] Pointer to one of the records in the metafile. This record should not be modified. (If modification is necessary, it should be performed on a copy of the record.)
nObj
[in] Specifies the number of objects with associated handles in the handle table.
lpData
[in] Pointer to optional data.

Return Values

This function must return a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register the callback function by passing its address to the EnumEnhMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Functions, ENHMETARECORD, EnumEnhMetaFile, HANDLETABLE


EnumEnhMetaFile

The EnumEnhMetaFile function enumerates the records within an enhanced-format metafile by retrieving each record and passing it to the specified callback function. The application-supplied callback function processes each record as required. The enumeration continues until the last record is processed or when the callback function returns zero.

BOOL EnumEnhMetaFile(
  HDC hdc,                     // handle to DC
  HENHMETAFILE hemf,           // handle to enhanced metafile
  ENHMFENUMPROC lpEnhMetaFunc, // callback function
  LPVOID lpData,               // callback-function data
  CONST RECT *lpRect           // bounding rectangle
);

Parameters

hdc
[in] Handle to a device context. This handle is passed to the callback function.
hemf
[in] Handle to an enhanced metafile.
lpEnhMetaFunc
[in] Pointer to the application-supplied callback function. For more information, see the EnhMetaFileProc function.
lpData
[in] Pointer to optional callback-function data.
lpRect
[in] Pointer to a RECT structure that specifies the coordinates of the picture's upper-left and lower-right corners. The dimensions of this rectangle are specified in logical units.

Return Values

If the callback function successfully enumerates all the records in the enhanced metafile, the return value is nonzero.

If the callback function does not successfully enumerate all the records in the enhanced metafile, the return value is zero.

Remarks

Points along the edge of the rectangle pointed to by the lpRect parameter are included in the picture. If the hdc parameter is NULL, the system ignores lpRect.

If the callback function calls the PlayEnhMetaFileRecord function, hdc must identify a valid device context. The system uses the device context's transformation and mapping mode to transform the picture displayed by the PlayEnhMetaFileRecord function.

You can use the EnumEnhMetaFile function to embed one enhanced-metafile within another.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, EnhMetaFileProc, PlayEnhMetaFile, PlayEnhMetaFileRecord, RECT


EnumMetaFile

The EnumMetaFile function enumerates the records within a Windows-format metafile by retrieving each record and passing it to the specified callback function. The application-supplied callback function processes each record as required. The enumeration continues until the last record is processed or when the callback function returns zero.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the EnumEnhMetaFile function.

BOOL EnumMetaFile(
  HDC hdc,                // handle to DC
  HMETAFILE hmf,          // handle to Windows-format metafile
  MFENUMPROC lpMetaFunc,  // callback function
  LPARAM lParam           // optional data
);

Parameters

hdc
[in] Handle to a device context. This handle is passed to the callback function.
hmf
[in] Handle to a Windows-format metafile.
lpMetaFunc
[in] Pointer to an application-supplied callback function. For more information, see EnumMetaFileProc.
lParam
[in] Pointer to optional data.

Return Values

If the callback function successfully enumerates all the records in the Windows-format metafile, the return value is nonzero.

If the callback function does not successfully enumerate all the records in the Windows-format metafile, the return value is zero.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

You can use the EnumMetaFile function to embed one Windows-format metafile within another.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, EnumEnhMetaFile, EnumMetaFileProc, PlayMetaFile, PlayMetaFileRecord, PolyBezier, SetWinMetaFileBits, SetWorldTransform


EnumMetaFileProc

The EnumMetaFileProc function is an application-defined callback function that processes Windows-format metafile records. This function is called by the EnumMetaFile function. The MFENUMPROC type defines a pointer to this callback function. EnumMetaFileProc is a placeholder for the application-defined function name.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the EnhMetaFileProc and EnumEnhMetaFile functions.

int CALLBACK EnumMetaFileProc(
  HDC hDC,                // handle to DC
  HANDLETABLE *lpHTable,  // metafile handle table
  METARECORD *lpMFR,      // metafile record
  int nObj,               // count of objects
  LPARAM lpClientData     // optional data
);

Parameters

hDC
[in] Handle to the device context passed to EnumMetaFile.
lpHTable
[in] Pointer to a table of handles associated with the graphics objects (pens, brushes, and so on) in the metafile.
lpMFR
[in] Pointer to one of the records in the metafile. This record should not be modified. (If modification is necessary, it should be performed on a copy of the record.)
nObj
[in] Specifies the number of objects with associated handles in the handle table.
lpClientData
[in] Pointer to optional data.

Return Values

This function must return a nonzero value to continue enumeration; to stop enumeration, it must return zero.

Remarks

An application must register the callback function by passing its address to the EnumMetaFile function.

EnumMetaFileProc is a placeholder for the application-supplied function name.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Functions, EnhMetaFileProc, EnumEnhMetaFile, EnumMetaFile


GdiComment

The GdiComment function copies a comment from a buffer into a specified enhanced-format metafile.

BOOL GdiComment(
  HDC hdc,             // handle to a device context
  UINT cbSize,         // size of text buffer
  CONST BYTE *lpData   // text buffer
);

Parameters

hdc
[in] Handle to an enhanced-metafile device context.
cbSize
[in] Specifies the length of the comment buffer, in bytes.
lpData
[in] Pointer to the buffer that contains the comment.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A comment can include any kind of private information—for example, the source of a picture and the date it was created. A comment should begin with an application signature, followed by the data.

Comments should not contain application-specific or 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.

A public comment is a comment that begins with the comment signature identifier GDICOMMENT_IDENTIFIER. The following public comments are defined.

GDICOMMENT_WINDOWS_METAFILE The GDICOMMENT_WINDOWS_METAFILE public comment contains a Windows-format metafile that is equivalent to an enhanced-format metafile. This comment is written only by the SetWinMetaFileBits function. The comment record, if given, follows the ENHMETAHEADER metafile record. The comment has the following form:

DWORD ident;         // This contains GDICOMMENT_IDENTIFIER.
DWORD iComment;      // This contains GDICOMMENT_WINDOWS_METAFILE.
DWORD nVersion;      // This contains the version number of the
                     // Windows-format metafile.
DWORD nChecksum;     // This is the additive DWORD checksum for
                     // the enhanced metafile.  The checksum
                     // for the enhanced metafile data including
                     // this comment record must be zero.
                     // Otherwise, the enhanced metafile has been
                     //  modified and the Windows-format
                     // metafile is no longer valid.
DWORD fFlags;        // This must be zero.
DWORD cbWinMetaFile; // This is the size, in bytes. of the
                     // Windows-format metafile data that follows.
GDICOMMENT_BEGINGROUP The GDICOMMENT_BEGINGROUP public comment identifies the beginning of a group of drawing records. It identifies an object within an enhanced metafile. The comment has the following form:

DWORD   ident;         // This contains GDICOMMENT_IDENTIFIER.
DWORD   iComment;      // This contains GDICOMMENT_BEGINGROUP.
RECTL   rclOutput;     // This is the bounding rectangle for the
                       // object in logical coordinates.
DWORD   nDescription;  // This is the number of characters in the
                       // optional Unicode description string that
                       // follows. This is zero if there is no
                       // description string.
GDICOMMENT_ENDGROUP The GDICOMMENT_ENDGROUP public comment identifies the end of a group of drawing records. The GDICOMMENT_BEGINGROUP comment and the GDICOMMENT_ENDGROUP comment must be included in a pair and may be nested. The comment has the following form:

DWORD   ident;       // This contains GDICOMMENT_IDENTIFIER.
DWORD   iComment;    // This contains GDICOMMENT_ENDGROUP.
GDICOMMENT_MULTIFORMATS Windows NT 4.0 SP4 and earlier, Windows 95/98/Me: The GDICOMMENT_MULTIFORMATS public comment allows multiple definitions of a picture to be included in an enhanced metafile. Using this comment, for example, an application can include an encapsulated PostScript definition as well as an enhanced metafile definition of a picture. When the record is played back, GDI selects and renders the first format recognized by the device. The comment has the following form:

DWORD   ident;          // This contains GDICOMMENT_IDENTIFIER.
DWORD   iComment;       // This contains GDICOMMENT_MULTIFORMATS.
RECTL   rclOutput;      // This is the bounding rectangle for the
                        // picture in logical coordinates.
DWORD   nFormats;       // This contains the number of formats in
                        // the comment.
EMRFORMAT aemrformat[1];// This is an array of EMRFORMAT structures
                        // in the order of preference.  The data
                        // for each format follows the last
                        // EMRFORMAT structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CreateEnhMetaFile, SetWinMetaFileBits


GetEnhMetaFile

The GetEnhMetaFile function creates a handle that identifies the enhanced-format metafile stored in the specified file.

HENHMETAFILE GetEnhMetaFile(
  LPCTSTR lpszMetaFile   // file name
);

Parameters

lpszMetaFile
[in] Pointer to a null-terminated string that specifies the name of an enhanced metafile.

Return Values

If the function succeeds, the return value is a handle to the enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When the application no longer needs an enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

A Windows-format metafile must be converted to the enhanced format before it can be processed by the GetEnhMetaFile function. To convert the file, use the SetWinMetaFileBits function.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

Windows 95/98/Me: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

For an example, see Opening an Enhanced Metafile and Displaying Its Contents.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile, GetEnhMetaFile, SetWinMetaFileBits


GetEnhMetaFileBits

The GetEnhMetaFileBits function retrieves the contents of the specified enhanced-format metafile and copies them into a buffer.

UINT GetEnhMetaFileBits(
  HENHMETAFILE hemf, // handle to metafile
  UINT cbBuffer,     // size of data buffer
  LPBYTE lpbBuffer   // data buffer
);

Parameters

hemf
[in] Handle to the enhanced metafile.
cbBuffer
[in] Specifies the size, in bytes, of the buffer to receive the data.
lpbBuffer
[out] Pointer to a buffer that receives the metafile data. The buffer must be sufficiently large to contain the data. If lpbBuffer is NULL, the function returns the size necessary to hold the data.

Return Values

If the function succeeds and the buffer pointer is NULL, the return value is the size of the enhanced metafile, in bytes.

If the function succeeds and the buffer pointer is a valid pointer, the return value is the number of bytes copied to the buffer.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

After the enhanced-metafile bits are retrieved, they can be used to create a memory-based metafile by calling the SetEnhMetaFileBits function.

The GetEnhMetaFileBits function does not invalidate the enhanced-metafile handle. The application must call the DeleteEnhMetaFile function to delete the handle when it is no longer needed.

The metafile contents retrieved by this function are in the enhanced format. To retrieve the metafile contents in the Windows format, use the GetWinMetaFileBits function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile, GetWinMetaFileBits, SetEnhMetaFileBits


GetEnhMetaFileDescription

The GetEnhMetaFileDescription function retrieves an optional text description from an enhanced-format metafile and copies the string to the specified buffer.

UINT GetEnhMetaFileDescription(
  HENHMETAFILE hemf,       // handle to enhanced metafile
  UINT cchBuffer,          // size of text buffer
  LPTSTR lpszDescription   // text buffer
);

Parameters

hemf
[in] Handle to the enhanced metafile.
cchBuffer
[in] Specifies the size, in characters, of the buffer to receive the data. Only this many characters will be copied.
lpszDescription
[out] Pointer to a buffer that receives the optional text description.

Return Values

If the optional text description exists and the buffer pointer is NULL, the return value is the length of the text string, in characters.

If the optional text description exists and the buffer pointer is a valid pointer, the return value is the number of characters copied into the buffer.

If the optional text description does not exist, the return value is zero.

If the function fails, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The optional text description contains two strings, the first identifying the application that created the enhanced metafile and the second identifying the picture contained in the metafile. The strings are separated by a null character and terminated with two null characters—for example, "XYZ Graphics Editor\0Bald Eagle\0\0" where \0 represents the null character.

Where text arguments must use Unicode characters, use this function as a wide-character function. Where text arguments must use characters from the Windows character set, use this function as an ANSI function.

Windows 95/98/Me: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Metafiles Overview, Metafile Functions, CreateEnhMetaFile


GetEnhMetaFileHeader

The GetEnhMetaFileHeader function retrieves the record containing the header for the specified enhanced-format metafile.

UINT GetEnhMetaFileHeader(
  HENHMETAFILE hemf,      // handle to enhanced metafile
  UINT cbBuffer,          // size of buffer
  LPENHMETAHEADER lpemh   // data buffer
);

Parameters

hemf
[in] Handle to the enhanced metafile for which the header is to be retrieved.
cbBuffer
[in] Specifies the size, in bytes, of the buffer to receive the data. Only this many bytes will be copied.
lpemh
[out] Pointer to an ENHMETAHEADER structure that receives the header record. If this parameter is NULL, the function returns the size of the header record.

Return Values

If the function succeeds and the structure pointer is NULL, the return value is the size of the record that contains the header; if the structure pointer is a valid pointer, the return value is the number of bytes copied. Otherwise, it is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An enhanced-metafile header contains such information as the metafile's size, in bytes; the dimensions of the picture stored in the metafile; the number of records stored in the metafile; the offset to the optional text description; the size of the optional palette, and the resolution of the device on which the picture was created.

The record that contains the enhanced-metafile header is always the first record in the metafile.

Windows 95/98/Me: The maximum length of the description string for an enhanced metafile is 16,384 bytes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, ENHMETAHEADER, PlayEnhMetaFile


GetEnhMetaFilePaletteEntries

The GetEnhMetaFilePaletteEntries function retrieves optional palette entries from the specified enhanced metafile.

UINT GetEnhMetaFilePaletteEntries(
  HENHMETAFILE hemf,    // handle to enhanced metafile
  UINT cEntries,        // count of palette entries
  LPPALETTEENTRY lppe   // array of palette entries
);

Parameters

hemf
[in] Handle to the enhanced metafile.
cEntries
[in] Specifies the number of entries to be retrieved from the optional palette.
lppe
[out] Pointer to an array of PALETTEENTRY structures that receives the palette colors. The array must contain at least as many structures as there are entries specified by the cEntries parameter.

Return Values

If the array pointer is NULL and the enhanced metafile contains an optional palette, the return value is the number of entries in the enhanced metafile's palette; if the array pointer is a valid pointer and the enhanced metafile contains an optional palette, the return value is the number of entries copied; if the metafile does not contain an optional palette, the return value is zero. Otherwise, the return value is GDI_ERROR.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

An application can store an optional palette in an enhanced metafile by calling the CreatePalette and SetPaletteEntries functions before creating the picture and storing it in the metafile. By doing this, the application can achieve consistent colors when the picture is displayed on a variety of devices.

An application that displays a picture stored in an enhanced metafile can call the GetEnhMetaFilePaletteEntries function to determine whether the optional palette exists. If it does, the application can call the GetEnhMetaFilePaletteEntries function a second time to retrieve the palette entries and then create a logical palette (by using the CreatePalette function), select it into its device context (by using the SelectPalette function), and then realize it (by using the RealizePalette function). After the logical palette has been realized, calling the PlayEnhMetaFile function displays the picture using its original colors.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CreatePalette, PALETTEENTRY, PlayEnhMetaFile, RealizePalette, SelectPalette


GetMetaFileBitsEx

The GetMetaFileBitsEx function retrieves the contents of a Windows-format metafile and copies them into the specified buffer.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the GetEnhMetaFileBits function.

UINT GetMetaFileBitsEx(
  HMETAFILE hmf,  // handle to metafile
  UINT nSize,     // size of metafile
  LPVOID lpvData  // metafile data
);

Parameters

hmf
[in] Handle to a Windows-format metafile.
nSize
[in] Specifies the size, in bytes, of the buffer to receive the data.
lpvData
[out] Pointer to a buffer that receives the metafile data. The buffer must be sufficiently large to contain the data. If lpvData is NULL, the function returns the number of bytes required to hold the data.

Return Values

If the function succeeds and the buffer pointer is NULL, the return value is the number of bytes required for the buffer; if the function succeeds and the buffer pointer is a valid pointer, the return value is the number of bytes copied.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

After the Windows-metafile bits are retrieved, they can be used to create a memory-based metafile by calling the SetMetaFileBitsEx function.

The GetMetaFileBitsEx function does not invalidate the metafile handle. An application must delete this handle by calling the DeleteMetaFile function.

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, DeleteMetaFile, GetEnhMetaFileBits, PolyBezier, SetMetaFileBitsEx, SetWinMetaFileBits, SetWorldTransform


GetWinMetaFileBits

The GetWinMetaFileBits function converts the enhanced-format records from a metafile into Windows-format records and stores the converted records in the specified buffer.

UINT GetWinMetaFileBits(
  HENHMETAFILE hemf, // handle to the enhanced metafile
  UINT cbBuffer,     // buffer size
  LPBYTE lpbBuffer,  // records buffer
  INT fnMapMode,     // mapping mode
  HDC hdcRef         // handle to reference DC
);

Parameters

hemf
[in] Handle to the enhanced metafile.
cbBuffer
[in] Specifies the size, in bytes, of the buffer into which the converted records are to be copied.
lpbBuffer
[out] Pointer to the buffer that receives the converted records. If lpbBuffer is NULL, GetWinMetaFileBits returns the number of bytes required to store the converted metafile records.
fnMapMode
[in] Specifies the mapping mode to use in the converted metafile.
hdcRef
[in] Handle to the reference device context.

Return Values

If the function succeeds and the buffer pointer is NULL, the return value is the number of bytes required to store the converted records; if the function succeeds and the buffer pointer is a valid pointer, the return value is the size of the metafile data in bytes.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This function converts an enhanced metafile into a Windows-format metafile so that its picture can be displayed in an application that recognizes the older format.

The system uses the reference device context to determine the resolution of the converted metafile.

The GetWinMetaFileBits function does not invalidate the enhanced metafile handle. An application should call the DeleteEnhMetaFile function to release the handle when it is no longer needed.

Due to the limitations of the Windows-format metafile, some information can be lost in the retrieved metafile contents. For example, an original call to the PolyBezier function in the enhanced metafile may be converted into a call to the Polyline function in the Windows-format metafile, because there is no equivalent PolyBezier function in the Windows format.

16-bit Windows-based applications define the viewport origin and extents of a picture stored in a Windows-format metafile. As a result, the Windows-format records created by GetWinMetaFileBits do not contain the SetViewportOrgEx and SetViewportExtEx functions. However, GetWinMetaFileBits does create Windows-format records for the SetWindowExtEx and SetMapMode functions.

To create a scalable Windows-format metafile, specify MM_ANISOTROPIC as the fnMapMode parameter.

The upper-left corner of the metafile picture is always mapped to the origin of the reference device.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile, PolyBezier, Polyline, SetMapMode, SetViewportOrgEx, SetViewportExtEx, SetWindowExtEx, SetWinMetaFileBits


PlayEnhMetaFile

The PlayEnhMetaFile function displays the picture stored in the specified enhanced-format metafile.

BOOL PlayEnhMetaFile(
  HDC hdc,            // handle to DC
  HENHMETAFILE hemf,  // handle to an enhanced metafile
  CONST RECT *lpRect  // bounding rectangle
);

Parameters

hdc
[in] Handle to the device context for the output device on which the picture will appear.
hemf
[in] Handle to the enhanced metafile.
lpRect
[in] Pointer to a RECT structure that contains the coordinates of the bounding rectangle used to display the picture. The coordinates are specified in logical units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When an application calls the PlayEnhMetaFile function, the system uses the picture frame in the enhanced-metafile header to map the picture onto the rectangle pointed to by the lpRect parameter. (This picture may be sheared or rotated by setting the world transform in the output device before calling PlayEnhMetaFile.) 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 PlayEnhMetaFile. To retrieve the optional palette, use the GetEnhMetaFilePaletteEntries function.

An enhanced metafile can be embedded in a newly created enhanced metafile by calling PlayEnhMetaFile 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 function from another thread to terminate the operation. In this case, the function returns FALSE.

Windows 95/98/Me: PlayEnhMetaFile is subject to the limitations of the GDI. For example, Windows 95/98 supports only 16-bit signed coordinates. For records that contain 32-bit values, Windows 95/98 fails to play the record if the values are not in the range –32,768 to 32,767.

For an example, see Opening an Enhanced Metafile and Displaying Its Contents.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, CancelDC, GetEnhMetaFileHeader, GetEnhMetaFilePaletteEntries, RECT, SetWorldTransform


PlayEnhMetaFileRecord

The PlayEnhMetaFileRecord function plays an enhanced-metafile record by executing the graphics device interface (GDI) functions identified by the record.

BOOL PlayEnhMetaFileRecord(
  HDC hdc,                              // handle to DC
  LPHANDLETABLE lpHandletable,          // metafile handle table
  CONST ENHMETARECORD *lpEnhMetaRecord, // metafile record
  UINT nHandles                         // count of handles
);

Parameters

hdc
[in] Handle to the device context passed to the EnumEnhMetaFile function.
lpHandletable
[in] Pointer to a table of handles to GDI objects used when playing the metafile. The first entry in this table contains the enhanced-metafile handle.
lpEnhMetaRecord
[in] Pointer to the enhanced-metafile record to be played.
nHandles
[in] Specifies the number of handles in the handle table.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This is an enhanced-metafile function.

An application typically uses PlayEnhMetaFileRecord in conjunction with the EnumEnhMetaFile function to process and play an enhanced-format metafile one record at a time.

The hdc, lpHandletable, and nHandles parameters must be exactly those passed to the EnhMetaFileProc callback procedure by the EnumEnhMetaFile function.

If PlayEnhMetaFileRecord does not recognize a record, it ignores the record and returns TRUE.

Windows 95/98/Me: PlayEnhMetaFileRecord is subject to the limitations of GDI. For example, Windows 95/98 supports only 16-bit signed coordinates. For records that contain 32-bit values, Windows 95/98 fails to play the record if the values are not in the range –32,768 to 32,767.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, EnumEnhMetaFile, PlayEnhMetaFile


PlayMetaFile

The PlayMetaFile function displays the picture stored in the given Windows-format metafile on the specified device.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the PlayEnhMetaFile function.

BOOL PlayMetaFile(
  HDC hdc,        // handle to DC
  HMETAFILE hmf   // handle to metafile
);

Parameters

hdc
[in] Handle to a device context.
hmf
[in] Handle to a Windows-format metafile.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced format metafile, use the SetWinMetaFileBits function.

A Windows-format metafile can be played multiple times.

A Windows-format metafile can be embedded in a second Windows-format metafile by calling the PlayMetaFile function and playing the source metafile into the device context for the target metafile.

Any object created but not deleted in the Windows-format metafile is deleted by this function.

To stop this function, an application can call the CancelDC function from another thread to terminate the operation. In this case, the function returns FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, CancelDC, PolyBezier, SetWinMetaFileBits, SetWorldTransform


PlayMetaFileRecord

The PlayMetaFileRecord function plays a Windows-format metafile record by executing the graphics device interface (GDI) function contained within that record.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the PlayEnhMetaFileRecord function.

BOOL PlayMetaFileRecord(
  HDC hdc,                      // handle to DC
  LPHANDLETABLE lpHandletable,  // metafile handle table
  LPMETARECORD lpMetaRecord,    // metafile record
  UINT nHandles                 // count of handles
);

Parameters

hdc
[in] Handle to a device context.
lpHandletable
[in] Pointer to a HANDLETABLE structure representing the table of handles to GDI objects used when playing the metafile.
lpMetaRecord
[in] Pointer to the Windows-format metafile record.
nHandles
[in] Specifies the number of handles in the handle table.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions, such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions, should use the enhanced format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

An application typically uses PlayMetaFileRecord in conjunction with the EnumMetaFile function to process and play a Windows-format metafile one record at a time.

The lpHandletable and nHandles parameters must be identical to those passed to the EnumMetaFileProc callback procedure by EnumMetaFile.

If the PlayMetaFileRecord function does not recognize a record, it ignores the record and returns TRUE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, EnumMetaFile, HANDLETABLE, METARECORD, PlayMetaFile, PolyBezier, SetWinMetaFileBits, SetWorldTransform


SetEnhMetaFileBits

The SetEnhMetaFileBits function creates a memory-based enhanced-format metafile from the specified data.

HENHMETAFILE SetEnhMetaFileBits(
  UINT cbBuffer,      // buffer size
  CONST BYTE *lpData  // enhanced metafile data buffer
);

Parameters

cbBuffer
[in] Specifies the size, in bytes, of the data provided.
lpData
[in] Pointer to a buffer that contains enhanced-metafile data. (It is assumed that the data in the buffer was obtained by calling the GetEnhMetaFileBits function.)

Return Values

If the function succeeds, the return value is a handle to a memory-based enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When the application no longer needs the enhanced-metafile handle, it should delete the handle by calling the DeleteEnhMetaFile function.

The SetEnhMetaFileBits function does not accept metafile data in the Windows format. To import Windows-format metafiles, use the SetWinMetaFileBits function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile, GetEnhMetaFileBits, SetWinMetaFileBits


SetMetaFileBitsEx

The SetMetaFileBitsEx function creates a memory-based Windows-format metafile from the supplied data.

Note This function is provided only for compatibility with 16-bit versions of Windows. Win32-based applications should use the SetEnhMetaFileBits function.

HMETAFILE SetMetaFileBitsEx(
  UINT nSize,          // size of Windows-format metafile
  CONST BYTE *lpData   // metafile data
);

Parameters

nSize
[in] Specifies the size, in bytes, of the Windows-format metafile.
lpData
[in] Pointer to a buffer that contains the Windows-format metafile. (It is assumed that the data was obtained by using the GetMetaFileBitsEx function.)

Return Values

If the function succeeds, the return value is a handle to a memory-based Windows-format metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

A Windows-format metafile does not support the new curve, path, and transformation functions such as PolyBezier, BeginPath, and SetWorldTransform. Applications that use these new functions and use metafiles to store pictures created by these functions should use the enhanced-format metafile functions.

To convert a Windows-format metafile into an enhanced-format metafile, use the SetWinMetaFileBits function.

When the application no longer needs the metafile handle returned by SetMetaFileBitsEx, it should delete it by calling the DeleteMetaFile function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, BeginPath, DeleteMetaFile, GetMetaFileBitsEx, PolyBezier, SetEnhMetaFileBits, SetWinMetaFileBits, SetWorldTransform


SetWinMetaFileBits

The SetWinMetaFileBits function converts a metafile from the older Windows format to the new enhanced format and stores the new metafile in memory.

HENHMETAFILE SetWinMetaFileBits(
  UINT cbBuffer,              // size of buffer
  CONST BYTE *lpbBuffer,      // metafile data buffer
  HDC hdcRef,                 // handle to reference DC
  CONST METAFILEPICT *lpmfp   // size of metafile picture
);

Parameters

cbBuffer
[in] Specifies the size, in bytes, of the buffer that contains the Windows-format metafile.
lpbBuffer
[in] Pointer to a buffer that contains the Windows-format metafile data. (It is assumed that the data was obtained by using the GetMetaFileBitsEx or GetWinMetaFileBits function.)
hdcRef
[in] Handle to a reference device context.
lpmfp
[in] Pointer to a METAFILEPICT structure that contains the suggested size of the metafile picture and the mapping mode that was used when the picture was created.

Return Values

If the function succeeds, the return value is a handle to a memory-based enhanced metafile.

If the function fails, the return value is NULL.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The Win32 API uses the reference device context's resolution data and the data in the METAFILEPICT structure to scale a picture. If the hdcRef parameter is NULL, the system uses resolution data for the current output device. If the lpmfp parameter is NULL, the system uses the MM_ANISOTROPIC mapping mode to scale the picture so that it fits the entire device surface. The hMF field in the METAFILEPICT structure is not used.

When the application no longer needs the enhanced metafile handle, it should delete it by calling the DeleteEnhMetaFile function.

The handle returned by this function can be used with other enhanced-metafile functions.

If the reference device context is not identical to the device in which the metafile was originally created, some GDI functions that use device units may not draw the picture correctly.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Metafiles Overview, Metafile Functions, DeleteEnhMetaFile, GetWinMetaFileBits, GetMetaFileBitsEx, METAFILEPICT, PlayEnhMetaFile


Metafile Structures

The following structures are used with enhanced-format metafiles.

EMRTEXT
EMRTRANSPARENTBLT
EMRWIDENPATH
ENHMETAHEADER
ENHMETARECORD
HANDLETABLE
POINTL
RECTL

Note that the EMR structure is used as the first member of the remaining structures.

EMR
EMRABORTPATH
EMRALPHABLEND
EMRANGLEARC
EMRARC
EMRARCTO
EMRBEGINPATH
EMRBITBLT
EMRCHORD
EMRCLOSEFIGURE
EMRCOLORCORRECTPALETTE
EMRCOLORMATCHTOTARGET
EMRCREATEBRUSHINDIRECT
EMRCREATECOLORSPACE
EMRCREATECOLORSPACEW
EMRCREATEDIBPATTERNBRUSHPT
EMRCREATEMONOBRUSH
EMRCREATEPALETTE
EMRCREATEPEN
EMRDELETECOLORSPACE
EMRDELETEOBJECT
EMRELLIPSE
EMRENDPATH
EMREOF
EMREXCLUDECLIPRECT
EMREXTCREATEFONTINDIRECTW
EMREXTCREATEPEN
EMREXTFLOODFILL
EMREXTSELECTCLIPRGN
EMREXTTEXTOUTA
EMREXTTEXTOUTW
EMRFILLPATH
EMRFILLRGN
EMRFLATTENPATH
EMRFORMAT
EMRFRAMERGN
EMRGDICOMMENT
EMRGLSBOUNDEDRECORD
EMRGLSRECORD
EMRGRADIENTFILL
EMRINTERSECTCLIPRECT
EMRINVERTRGN
EMRLINETO
EMRMASKBLT
EMRMODIFYWORLDTRANSFORM
EMRMOVETOEX
EMROFFSETCLIPRGN
EMRPAINTRGN
EMRPIE
EMRPIXELFORMAT
EMRPLGBLT
EMRPOLYBEZIER
EMRPOLYBEZIER16
EMRPOLYBEZIERTO
EMRPOLYBEZIERTO16
EMRPOLYDRAW
EMRPOLYDRAW16
EMRPOLYGON
EMRPOLYGON16
EMRPOLYLINE
EMRPOLYLINE16
EMRPOLYLINETO
EMRPOLYLINETO16
EMRPOLYPOLYGON
EMRPOLYPOLYGON16
EMRPOLYPOLYLINE
EMRPOLYPOLYLINE16
EMRPOLYTEXTOUTA
EMRPOLYTEXTOUTW
EMRREALIZEPALETTE
EMRRECTANGLE
EMRRESIZEPALETTE
EMRRESTOREDC
EMRROUNDRECT
EMRSAVEDC
EMRSCALEVIEWPORTEXTEX
EMRSCALEWINDOWEXTEX
EMRSELECTCLIPPATH
EMRSELECTCOLORSPACE
EMRSELECTOBJECT
EMRSELECTPALETTE
EMRSETARCDIRECTION
EMRSETBKCOLOR
EMRSETBKMODE
EMRSETBRUSHORGEX
EMRSETCOLORADJUSTMENT
EMRSETCOLORSPACE
EMRSETDIBITSTODEVICE
EMRSETICMMODE
EMRSETICMPROFILE
EMRSETLAYOUT
EMRSETMAPMODE
EMRSETMAPPERFLAGS
EMRSETMETARGN
EMRSETMITERLIMIT
EMRSETPALETTEENTRIES
EMRSETPIXELV
EMRSETPOLYFILLMODE
EMRSETROP2
EMRSETSTRETCHBLTMODE
EMRSETTEXTALIGN
EMRSETTEXTCOLOR
EMRSETVIEWPORTEXTEX
EMRSETVIEWPORTORGEX
EMRSETWINDOWEXTEX
EMRSETWINDOWORGEX
EMRSETWORLDTRANSFORM
EMRSTRETCHBLT
EMRSTRETCHDIBITS
EMRSTROKEANDFILLPATH
EMRSTROKEPATH

Obsolete Structures

The following structures are obsolete. The are provided for compatibility with Windows-format metafiles:

METAHEADER
METARECORD


EMR

The EMR structure provides the base structure for all enhanced metafile records. An enhanced metafile record contains the parameters for a specific GDI function used to create part of a picture in an enhanced format metafile.

typedef struct tagEMR {
  DWORD iType;
  DWORD nSize;
} EMR, *PEMR;

Members

iType
Specifies the record type. The parameter can be one of the following (with a link to the associated record structure).
EMR_ABORTPATH

EMR_ANGLEARC

EMR_ARC

EMR_ARCTO

EMR_BEGINPATH

EMR_BITBLT

EMR_CHORD

EMR_CLOSEFIGURE

EMR_CREATEBRUSHINDIRECT

EMR_CREATEDIBPATTERNBRUSHPT

EMR_CREATEMONOBRUSH

EMR_CREATEPALETTE

EMR_CREATEPEN

EMR_DELETEOBJECT

EMR_ELLIPSE

EMR_ENDPATH

EMR_EOF

EMR_EXCLUDECLIPRECT

EMR_EXTCREATEFONTINDIRECTW

EMR_EXTCREATEPEN

EMR_EXTFLOODFILL

EMR_EXTSELECTCLIPRGN

EMR_EXTTEXTOUTA

EMR_EXTTEXTOUTW

EMR_FILLPATH

EMR_FILLRGN

EMR_FLATTENPATH

EMR_FRAMERGN

EMR_GDICOMMENT

EMR_INTERSECTCLIPRECT

EMR_INVERTRGN

EMR_LINETO

EMR_MASKBLT

EMR_MODIFYWORLDTRANSFORM

EMR_MOVETOEX

EMR_OFFSETCLIPRGN

EMR_PAINTRGN

EMR_PIE

EMR_PLGBLT

EMR_POLYBEZIER

EMR_POLYBEZIER16

EMR_POLYBEZIERTO

EMR_POLYBEZIERTO16

EMR_POLYDRAW

EMR_POLYDRAW16

EMR_POLYGON

EMR_POLYGON16

EMR_POLYLINE

 EMR_POLYLINE16

EMR_POLYLINETO

EMR_POLYLINETO16

EMR_POLYPOLYGON

EMR_POLYPOLYGON16

EMR_POLYPOLYLINE

EMR_POLYPOLYLINE16

EMR_POLYTEXTOUTA

EMR_POLYTEXTOUTW

EMR_REALIZEPALETTE

EMR_RECTANGLE

EMR_RESIZEPALETTE

EMR_RESTOREDC

EMR_ROUNDRECT

EMR_SAVEDC

EMR_SCALEVIEWPORTEXTEX

EMR_SCALEWINDOWEXTEX

EMR_SELECTCLIPPATH

EMR_SELECTOBJECT

EMR_SELECTPALETTE

EMR_SETARCDIRECTION

EMR_SETBKCOLOR

EMR_SETBKMODE

EMR_SETBRUSHORGEX

EMR_SETCOLORADJUSTMENT

EMR_SETDIBITSTODEVICE

EMR_SETMAPMODE

EMR_SETMAPPERFLAGS

EMR_SETMETARGN

EMR_SETMITERLIMIT

EMR_SETPALETTEENTRIES

EMR_SETPIXELV

EMR_SETPOLYFILLMODE

EMR_SETROP2

EMR_SETSTRETCHBLTMODE

EMR_SETTEXTALIGN

EMR_SETTEXTCOLOR

EMR_SETVIEWPORTEXTEX

EMR_SETVIEWPORTORGEX

EMR_SETWINDOWEXTEX

EMR_SETWINDOWORGEX

EMR_SETWORLDTRANSFORM

EMR_STRETCHBLT

EMR_STRETCHDIBITS

EMR_STROKEANDFILLPATH

EMR_STROKEPATH

EMR_WIDENPATH

The following record types are valid for Windows 95 and Windows NT 4.0 and later.
EMR_CREATECOLORSPACE

EMR_DELETECOLORSPACE

EMR_GLSBOUNDEDRECORD

EMR_GLSRECORD

 EMR_PIXELFORMAT

EMR_SETCOLORSPACE

EMR_SETICMMODE

The following record types are valid for Windows 98 and Windows 2000 and later.
EMR_ALPHABLEND

EMR_COLORCORRECTPALETTE

EMR_COLORMATCHTOTARGETW

EMR_CREATECOLORSPACEW

EMR_GRADIENTFILL

 EMR_SETICMPROFILEA

EMR_SETICMPROFILEW

EMR_SETLAYOUT

EMR_TRANSPARENTBLT

nSize
Size of the record, in bytes. This member must be a multiple of four.

Re/quirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRALPHABLEND

The EMRALPHABLEND structure contains members for the AlphaBlend enhanced metafile record.

typedef struct tagEMRALPHABLEND {
  EMR     emr;
  RECTL   rclBounds;
  LONG    xDest;
  LONG    yDest;
  LONG    cxDest;
  LONG    cyDest;
  DWORD   dwRop;
  LONG    xSrc;
  LONG    ySrc;
  XFORM   xformSrc;
  COLORREF crBkColorSrc;
  DWORD   iUsageSrc;
  DWORD   offBmiSrc;
  DWORD   cbBmiSrc;
  DWORD   offBitsSrc;
  DWORD   cbBitsSrc;
  LONG    cxSrc;
  LONG    cySrc;
} EMRALPHABLEND, *PEMRALPHABLEND;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
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.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.
dwRop
Stores the BLENDFUNCTION structure.
xSrc
Logical x coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y coordinate of the upper-left corner of the source rectangle.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context. To make a COLORREF value, use the RGB macro.
iUsageSrc
Source bitmap information color table usage (DIB_RGB_COLORS).
offBmiSrc
Offset to the source BITMAPINFO structure.
cbBmiSrc
Size of the source BITMAPINFO structure.
offBitsSrc
Offset to the source bitmap bits.
cbBitsSrc
Size of the source bitmap bits.
cxSrc
Width of source rectangle in logical units.
cySrc
Height of the source rectangle in logical units.

Remarks

This structure is to be used during metafile playback.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, AlphaBlend, COLORREF, RGB


EMRANGLEARC

The EMRANGLEARC structure contains members for the AngleArc enhanced metafile record.

typedef struct tagEMRANGLEARC {
  EMR     emr;
  POINTL  ptlCenter;
  DWORD   nRadius;
  FLOAT   eStartAngle;
  FLOAT   eSweepAngle;
} EMRANGLEARC, *PEMRANGLEARC;

Members

emr
Base structure for all record types.
ptlCenter
Logical coordinates of a circle's center.
nRadius
A circle's radius, in logical units.
eStartAngle
An arc's start angle, in degrees.
eSweepAngle
An arc's sweep angle, in degrees.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, AngleArc


EMRARC, EMRARCTO, EMRCHORD, EMRPIE

The EMRARC, EMRARCTO, EMRCHORD, and EMRPIE structures contain members for the Arc, ArcTo, Chord, and Pie enhanced metafile records.

typedef struct tagEMRARC {
  EMR    emr;
  RECTL  rclBox;
  POINTL ptlStart;
  POINTL ptlEnd;
} EMRARC,   *PEMRARC,
  EMRARCTO, *PEMRARCTO,
  EMRCHORD, *PEMRCHORD,
  EMRPIE,   *PEMRPIE;

Members

emr
Base structure for all record types.
rclBox
Bounding rectangle in logical units.
ptlStart
Coordinates of first radial ending point in logical units.
ptlEnd
Coordinates of second radial ending point in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRBITBLT

The EMRBITBLT structure contains members for the BitBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

typedef struct tagEMRBITBLT {
  EMR      emr;
  RECTL    rclBounds;
  LONG     xDest;
  LONG     yDest;
  LONG     cxDest;
  LONG     cyDest;
  DWORD    dwRop;
  LONG     xSrc;
  LONG     ySrc;
  XFORM    xformSrc;
  COLORREF crBkColorSrc;
  DWORD    iUsageSrc;
  DWORD    offBmiSrc;
  DWORD    cbBmiSrc;
  DWORD    offBitsSrc;
  DWORD    cbBitsSrc;
} EMRBITBLT, *PEMRBITBLT;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
xDest
Logical x-coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y-coordinate of the upper-left corner of the destination rectangle.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.
dwRop
Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.
xSrc
Logical x-coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y-coordinate of the upper-left corner of the source rectangle.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context. To make a COLORREF value, use the RGB macro.
iUsageSrc
Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmiSrc
Offset to source BITMAPINFO structure.
cbBmiSrc
Size of source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BitBlt, BITMAPINFO, COLORREF, RGB


EMRCOLORCORRECTPALETTE

The EMRCOLORCORRECTPALETTE structure contains members for the ColorCorrectPalette enhanced metafile record.

typedef struct tagCOLORCORRECTPALETTE {
  EMR      emr;
  DWORD    ihPalette;
  DWORD    nFirstEntry;
  DWORD    nPalEntries;
  DWORD    nReserved;
} EMRCOLORCORRECTPALETTE, *PEMRCOLORCORRECTPALETTE;

Members

emr
Base structure for all record types.
ihPalette
Index of the palette handle to color correct.
nFirstEntry
Index of the first entry in the palette to color correct.
nPalEntries
Number of palette entries to color correct.
nReserved
Reserved.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ColorCorrectPalette


EMRCOLORMATCHTOTARGET

The EMRCOLORMATCHTOTARGET structure contains members for the ColorMatchToTarget enhanced metafile record.

typedef struct tagCOLORMATCHTOTARGET {
  EMR   emr;
  DWORD dwAction;
  DWORD dwFlags;
  DWORD cbName;
  DWORD cbData;
  BYTE  Data[1];
} EMRCOLORMATCHTOTARGET, *PEMRCOLORMATCHTOTARGET;

Members

emr
Base structure for all record types.
dwAction
Action to be taken. This member can be one of the following values.
Action | Meaning
CS_ENABLE | Maps colors to the target device's color gamut. This enables color proofing. All subsequent draw commands to the DC will render colors as they would appear on the target device.
CS_DISABLE | Disables color proofing.
CS_DELETE_TRANSFORM | If color management is enabled for the target profile, disables it and deletes the concatenated transform.

dwFlags
This parameter can be the following value.
Flag | Meaning
COLORMATCHTOTARGET_EMBEDED | Indicates that a color profile has been embedded in the metafile.

cbName
Size of the desired target profile name, in bytes.
cbData
Size of the raw target profile data in bytes, if it is attached.
Data
An array containing the target profile name and the raw target profile data. The size of the array is cbName + cbData. If cbData is nonzero the raw target profile data is attached and follows the target profile name at location Data[cbName].

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ColorMatchToTarget


EMRCREATEBRUSHINDIRECT

The EMRCREATEBRUSHINDIRECT structure contains members for the CreateBrushIndirect enhanced metafile record.

typedef struct tagEMRCREATEBRUSHINDIRECT {
  EMR      emr;
  DWORD    ihBrush;
  LOGBRUSH32 lb;
} EMRCREATEBRUSHINDIRECT, *PEMRCREATEBRUSHINDIRECT;

Members

emr
Base structure for all record types.
ihBrush
Index of brush in handle table.
lb
LOGBRUSH32 structure containing information about the brush. The lbStyle member must be either the BS_SOLID, BS_HOLLOW, BS_NULL, or BS_HATCHED value.

Note, that if your code is used on both 32-bit and 64-bit platforms, you must use the LOGBRUSH32 structure. This maintains compatibility between the platforms when you record the metafile on one platform and use it on the other platform. If your code remains on one platform, it is sufficient to use LOGBRUSH.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreateBrushIndirect, LOGBRUSH, LOGBRUSH32


EMRCREATECOLORSPACE

The EMRCREATECOLORSPACE structure contains members for the CreateColorSpace enhanced metafile record.

typedef struct tagEMRCREATECOLORSPACE {
  EMR           emr;
  DWORD         ihCS;
  LOGCOLORSPACE lcs;
} EMRCREATECOLORSPACE, *PEMRCREATECOLORSPACE;

Members

emr
Base structure for all record types.
ihCS
Index of the color cpace in handle table.
lcs
Logical color space.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreateColorSpace , EMRCREATECOLORSPACEW


EMRCREATECOLORSPACEW

The EMRCREATECOLORSPACEW structure contains members for the CreateColorSpace enhanced metafile record. It differs from EMRCREATECOLORSPACE in that it has a Unicode logical color space and also has an optional array containing raw source profile data.

typedef struct tagEMRCREATECOLORSPACEW {
  EMR           emr;
  DWORD         ihCS;
  LOGCOLORSPACEW lcs;
  DWORD          dwFlags;
  DWORD          cbData;
  BYTE           Data[1];
} EMRCREATECOLORSPACEW, *PEMRCREATECOLORSPACEW;

Members

emr
Base structure for all record types.
ihCS
Index of the color cpace in handle table.
lcs
Logical color space. Note, this is the Unicode version of the structure.
dwFlags
Can be the following.
Flag | Meaning
CREATECOLORSPACE_EMBEDED | Indicates that a color space is embedded in the metafile.

cbData
Size of the raw source profile data in bytes, if it is attached.
Data
An array containing the source profile data. The size of the array is cbData.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreateColorSpace, EMRCREATECOLORSPACE


EMRCREATEDIBPATTERNBRUSHPT

The EMRCREATEDIBPATTERNBRUSHPT structure contains members for the CreateDIBPatternBrushPt enhanced metafile record. The BITMAPINFO structure is followed by the bitmap bits that form a packed device-independent bitmap (DIB).

typedef struct tagEMRCREATEDIBPATTERNBRUSHPT {
  EMR   emr;
  DWORD ihBrush;
  DWORD iUsage;
  DWORD offBmi;
  DWORD cbBmi;
  DWORD offBits;
  DWORD cbBits;
} EMRCREATEDIBPATTERNBRUSHPT,
PEMRCREATEDIBPATTERNBRUSHPT;

Members

emr
Base structure for all record types.
ihBrush
Index of brush in handle table.
iUsage
Value specifying whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indices. The iUsage member must be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmi
Offset to BITMAPINFO structure.
cbBmi
Size of BITMAPINFO structure.
offBits
Offset to bitmap bits.
cbBits
Size of bitmap bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, CreateDIBPatternBrushPt, RGB


EMRCREATEMONOBRUSH

The EMRCREATEMONOBRUSH structure contains members for the CreatePatternBrush (when passed a monochrome bitmap) or CreateDIBPatternBrush (when passed a monochrome DIB) enhanced metafile records.

typedef struct tagEMRCREATEMONOBRUSH {
  EMR   emr;
  DWORD ihBrush;
  DWORD iUsage;
  DWORD offBmi;
  DWORD cbBmi;
  DWORD offBits;
  DWORD cbBits;
} EMRCREATEMONOBRUSH, *PEMRCREATEMONOBRUSH;

Members

emr
Base structure for all record types.
ihBrush
Index of brush in handle table.
iUsage
Value specifying whether the bmiColors member of the BITMAPINFO structure was provided and, if so, whether bmiColors contains explicit red, green, blue (RGB) values or indices. The iUsage member must be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmi
Offset to BITMAPINFO structure.
cbBmi
Size of BITMAPINFO structure.
offBits
Offset to bitmap bits.
cbBits
Size of bitmap bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, CreateDIBPatternBrush, CreatePatternBrush, RGB


EMRCREATEPALETTE

The EMRCREATEPALETTE structure contains members for the CreatePalette enhanced metafile record.

typedef struct tagEMRCREATEPALETTE {
  EMR        emr;
  DWORD      ihPal;
  LOGPALETTE lgpl;
} EMRCREATEPALETTE, *PEMRCREATEPALETTE;

Members

emr
Base structure for all record types.
ihPal
Index of palette in handle table.
lgpl
LOGPALETTE structure that contains information about the palette. Note that peFlags members in the PALETTEENTRY structures do not contain any flags.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreatePalette, LOGPALETTE, PALETTEENTRY


EMRCREATEPEN

The EMRCREATEPEN structure contains members for the CreatePen enhanced metafile record.

typedef struct tagEMRCREATEPEN {
  EMR    emr;
  DWORD  ihPen;
  LOGPEN lopn;
} EMRCREATEPEN, *PEMRCREATEPEN;

Members

emr
Base structure for all record types
ihPen
Index to pen in handle table
lopn
Logical pen

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreatePen


EMRELLIPSE, EMRRECTANGLE

The EMRELLIPSE and EMARRECTANGLE structures contain members for the Ellipse and Rectangle enhanced metafile records.

typedef struct tagEMRELLIPSE {
  EMR   emr;
  RECTL rclBox;
} EMRELLIPSE,  *PEMRELLIPSE,
  EMRRECTANGLE, *PEMRRECTANGLE;

Members

emr
Base structure for all record types.
rclBox
Bounding rectangle in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, Ellipse, Rectangle


EMREOF

The EMREOF structure contains data for the enhanced metafile record that indicates the end of the metafile.

typedef struct tagEMREOF {
  EMR     emr;
  DWORD   nPalEntries;
  DWORD   offPalEntries;
  DWORD   nSizeLast;
} EMREOF, *PEMREOF;

Members

emr
Base structure for all record types.
nPalEntries
Number of palette entries.
offPalEntries
Offset to palette entries.
nSizeLast
Same size as the nSize member of the EMR structure. This member must be the last double word of the record. If palette entries exist, they precede this member.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, EMR


EMREXCLUDECLIPRECT, EMRINTERSECTCLIPRECT

The EMREXCLUDECLIPRECT and EMRINTERSECTCLIPRECTstructures contain members for the ExcludeClipRect and IntersectClipRect enhanced metafile records.

typedef struct tagEMREXCLUDECLIPRECT {
  EMR   emr;
  RECTL rclClip;
} EMREXCLUDECLIPRECT,   *PEMREXCLUDECLIPRECT,
  EMRINTERSECTCLIPRECT, *PEMRINTERSECTCLIPRECT;

Members

emr
Base structure for all record types.
rclClip
Clipping rectangle in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMREXTCREATEFONTINDIRECTW

The EMREXTCREATEFONTINDIRECTW structure contains members for the CreateFontIndirect enhanced metafile record.

typedef struct tagEMREXTCREATEFONTINDIRECTW {
  EMR         emr;
  DWORD       ihFont;
  EXTLOGFONTW elfw;
} EMREXTCREATEFONTINDIRECTW,
PEMREXTCREATEFONTINDIRECTW;

Members

emr
Base structure for all record types.
ihFont
Index to the font in handle table.
elfw
Logical font.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, CreateFontIndirect


EMREXTCREATEPEN

The EMREXTCREATEPEN structure contains members for the ExtCreatePen enhanced metafile record. If the record contains a BITMAPINFO structure, it is followed by the bitmap bits that form a packed device-independent bitmap (DIB).

typedef struct tagEMREXTCREATEPEN {
  EMR       emr;
  DWORD     ihPen;
  DWORD     offBmi;
  DWORD     cbBmi;
  DWORD     offBits;
  DWORD     cbBits;
  EXTLOGPEN elp;
} EMREXTCREATEPEN, *PEMREXTCREATEPEN;

Members

emr
Base structure for all record types.
ihPen
Index to pen in handle table.
offBmi
Offset to BITMAPINFO structure, if any.
cbBmi
Size of BITMAPINFO structure, if any.
offBits
Offset to brush bitmap bits, if any.
cbBits
Size of brush bitmap bits, if any.
elp
Extended logical pen, including the elpStyleEntry member of the EXTLOGPEN structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, ExtCreatePen, EXTLOGPEN


EMREXTFLOODFILL

The EMREXTFLOODFILL structure contains members for the ExtFloodFill enhanced metafile record.

typedef struct tagEMREXTFLOODFILL {
  EMR     emr;
  POINTL  ptlStart;
  COLORREF crColor;
  DWORD   iMode;
} EMREXTFLOODFILL, *PEMREXTFLOODFILL;

Members

emr
Base structure for all record types.
ptlStart
Coordinates where filling begins in logical units.
crColor
Color of fill. To make a COLORREF value, use the RGB macro.
iMode
Type of fill operation to be performed. This member must be either the FLOODFILLBORDER or FLOODFILLSURFACE value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ExtFloodFill, COLORREF, RGB


EMREXTSELECTCLIPRGN

The EMREXTSELECTCLIPRGN structure contains members for the ExtSelectClipRgn enhanced metafile record.

typedef struct tagEMREXTSELECTCLIPRGN {
  EMR   emr;
  DWORD cbRgnData;
  DWORD iMode;
  BYTE  RgnData[1];
} EMREXTSELECTCLIPRGN, *PEMREXTSELECTCLIPRGN;

Members

emr
Base structure for all record types.
cbRgnData
Size of region data, in bytes.
iMode
Operation to be performed. This member must be one of the following values: RGN_AND, RGN_COPY, RGN_DIFF, RGN_OR, or RGN_XOR.
RgnData
Buffer containing RGNDATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ExtSelectClipRgn


EMREXTTEXTOUTA, EMREXTTEXTOUTW

The EMREXTTEXTOUTA and EMREXTTEXTOUTW structures contain members for the ExtTextOut, TextOut, or DrawText enhanced metafile records.

typedef struct tagEMREXTTEXTOUTA {
  EMR     emr;
  RECTL   rclBounds;
  DWORD   iGraphicsMode;
  FLOAT   exScale;
  FLOAT   eyScale;
  EMRTEXT emrtext;
} EMREXTTEXTOUTA, *PEMREXTTEXTOUTA,
  EMREXTTEXTOUTW, *PEMREXTTEXTOUTW;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
iGraphicsMode
Current graphics mode. This member can be either the GM_COMPATIBLE or GM_ADVANCED value.
exScale
X-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.
eyScale
Y-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.
emrtext
EMRTEXT structure, which is followed by the string and the intercharacter spacing array.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRFILLPATH, EMRSTROKEANDFILLPATH, EMRSTROKEPATH

The EMRFILLPATH, EMRSTROKEANDFILLPATH, and EMRSTROKEPATH structures contain members for the FillPath, StrokeAndFillPath, and StrokePath enhanced metafile records.

typedef struct tagEMRFILLPATH {
  EMR   emr;
  RECTL rclBounds;
} EMRFILLPATH,          *PEMRFILLPATH,
  EMRSTROKEANDFILLPATH, *PEMRSTROKEANDFILLPATH,
  EMRSTROKEPATH,        *PEMRSTROKEPATH;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRFILLRGN

The EMRFILLRGN structure contains members for the FillRgn enhanced metafile record.

typedef struct tagEMRFILLRGN {
  EMR   emr;
  RECTL rclBounds;
  DWORD cbRgnData;
  DWORD ihBrush;
  BYTE  RgnData[1];
} EMRFILLRGN, *PEMRFILLRGN;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cbRgnData
Size of region data, in bytes.
ihBrush
Index of brush, in handle table.
RgnData
Buffer containing RGNDATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, FillRgn, RGNDATA


EMRFORMAT

The EMRFORMAT structure contains information that identifies graphics data in an enhanced metafile. A GDICOMMENT_MULTIFORMATS enhanced metafile public comment contains an array of EMRFORMAT structures.

typedef struct tagEMRFORMAT {
  DWORD   dSignature;
  DWORD   nVersion;
  DWORD   cbData;
  DWORD   offData;
} EMRFORMAT;

Members

dSignature
Contains a picture format identifier. The following identifier values are defined.
Identifier | Meaning
ENHMETA_SIGNATURE | The picture is in enhanced metafile format.
EPS_SIGNATURE | The picture is in encapsulated PostScript file format.

nVersion
Contains a picture version number. The following version number value is defined.
Version | Meaning
1 | This is the version number of a level 1 encapsulated PostScript file.

cbData
Specifies the size, in bytes, of the picture data.
offData
Specifies an offset to the picture data. The offset is figured from the start of the GDICOMMENT_MULTIFORMATS public comment within which this EMRFORMAT structure is embedded. The offset must be a DWORD offset.

Remarks

The reference page for GdiComment discusses enhanced metafile public comments in general, and the GDICOMMENT_MULTIFORMATS public comment in particular.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, GdiComment


EMRFRAMERGN

The EMRFRAMERGN structure contains members for the FrameRgn enhanced metafile record.

typedef struct tagEMRFRAMERGN {
  EMR   emr;
  RECTL rclBounds;
  DWORD cbRgnData;
  DWORD ihBrush;
  SIZEL szlStroke;
  BYTE  RgnData[1];
} EMRFRAMERGN, *PEMRFRAMERGN;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cbRgnData
Size of region data, in bytes.
ihBrush
Index of brush, in handle table.
szlStroke
Width and height of region frame.
RgnData
Buffer containing RGNDATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, FrameRgn, RGNDATA


EMRGDICOMMENT

The EMRGDICOMMENT structure contains application-specific data. This enhanced metafile record is only meaningful to applications that know the format of the data and how to utilize it. This record is ignored by graphics device interface (GDI) during playback of the enhanced metafile.

typedef struct tagEMRGDICOMMENT {
  EMR   emr;
  DWORD cbData;
  BYTE  Data[1];
} EMRGDICOMMENT, *PEMRGDICOMMENT;

Members

emr
Base structure for all record types.
cbData
Size of data buffer, in bytes.
Data[1]
Application-specific data.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRGLSBOUNDEDRECORD

The EMRGLSBOUNDEDRECORD structure contains members for an enhanced metafile record generated by OpenGL functions. It contains data for OpenGL functions with information in pixel units that must be scaled when playing the metafile.

typedef struct tagEMRGLSBOUNDEDRECORD {
  EMR    emr;         // base structure
  RECTL  rclBounds;   // bounds in recording coordinates
  DWORD  cbData;      // size of Data[], in bytes
  BYTE   Data[1];
} EMRGLSBOUNDEDRECORD, *PEMRGLSBOUNDEDRECORD;

Members

emr
Base structure for all record types.
rclBounds
Bounds of the rectangle, in recording coordinates, within which to perform the OpenGL function.
cbData
Size of Data, in bytes.
Data
Array of data representing the OpenGL function to be performed.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, OpenGL on Windows NT, Windows 2000, and Windows 95/98


EMRGLSRECORD

The EMRGLSRECORD structure contains members for an enhanced metafile record generated by OpenGL functions, It contains data for OpenGL functions that scale automatically to the OpenGL viewport.

typedef struct tagEMRGLSRECORD {
  EMR    emr;         // base structure
  DWORD  cbData;      // size of Data[], in bytes
  BYTE   Data[1];
} EMRGLSRECORD, *PEMRGLSRECORD;

Members

emr
Base structure for all records.
cbData
Size of Data, in bytes.
Data
Array of data representing the OpenGL function to be performed.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, OpenGL on Windows NT, Windows 2000, and Windows 95/98


EMRGRADIENTFILL

The EMRGRADIENTFILL structure contains members for the GradientFill enhanced metafile record.

typedef struct tagEMRGRADIENTFILL {
  EMR       emr;
  RECTL     rclBounds;
  DWORD     nVer;
  DWORD     nTri;
  ULONG     ulMode;
  TRIVERTEX Ver[1];
}EMRGRADIENTFILL,*PEMRGRADIENTFILL;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
nVer
Number of vertices.
nTri
Number of rectangles or triangles to pass to GradientFill.
ulMode
Specifies the gradient fill mode.
Ver[1]
Pointer to an array of TRIVERTEX structures that each define a triangle vertex.

Remarks

This is a variable-length structure. The nVer element designates the beginning of the variable-length area. First comes an array of nVer TRIVERTEX structures to pass the vertices. Next comes an array of either nTri GRADIENT_TRIANGLE structures or nTri GRADIENT_RECT structures, depending on the value of jlMode (triangles or rectangles).

This structure is to be used during metafile playback.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, Metafiles, BITMAPINFO, GradientFill, GRADIENT_TRIANGLE, GRADIENT_RECT


EMRINVERTRGN, EMRPAINTRGN

The EMRINVERTRGN and EMRPAINTRGN structures contain members for the InvertRgn and PaintRgn enhanced metafile records.

typedef struct tagEMRINVERTRGN {
  EMR   emr;
  RECTL rclBounds;
  DWORD cbRgnData;
  BYTE  RgnData[1];
} EMRINVERTRGN, *PEMRINVERTRGN,
  EMRPAINTRGN,  *PEMRPAINTRGN;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cbRgnData
Size of region data, in bytes.
RgnData
Buffer containing an RGNDATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, InvertRgn, PaintRgn


EMRLINETO, EMRMOVETOEX

The EMRLINETO and EMRMOVETOEX structures contains members for the LineTo and MoveToEx enhanced metafile records.

typedef struct tagEMRLINETO {
  EMR    emr;
  POINTL ptl;
} EMRLINETO,   *PEMRLINETO,
  EMRMOVETOEX, *PEMRMOVETOEX;

Members

emr
Base structure for all record types.
ptl
Coordinates of the line's ending point for the LineTo function or coordinates of the new current position for the MoveToEx function in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRMASKBLT

The EMRMASKBLT structure contains members for the MaskBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

typedef struct tagEMRMASKBLT {
  EMR     emr;
  RECTL   rclBounds;
  LONG    xDest;
  LONG    yDest;
  LONG    cxDest;
  LONG    cyDest;
  DWORD   dwRop;
  LONG    xSrc;
  LONG    ySrc;
  XFORM   xformSrc;
  COLORREF crBkColorSrc;
  DWORD   iUsageSrc;
  DWORD   offBmiSrc;
  DWORD   cbBmiSrc;
  DWORD   offBitsSrc;
  DWORD   cbBitsSrc;
  LONG    xMask;
  LONG    yMask;
  DWORD   iUsageMask;
  DWORD   offBmiMask;
  DWORD   cbBmiMask;
  DWORD   offBitsMask;
  DWORD   cbBitsMask;
} EMRMASKBLT, *PEMRMASKBLT;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
xDest
Logical x-coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y-coordinate of the upper-left corner of the destination rectangle.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.
dwRop
Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.
xSrc
Logical x-coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y-coordinate of the upper-left corner of the source rectangle.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context. To make a COLORREF value, use the RGB macro.
iUsageSrc
Value of the bmiColors member of the source BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmiSrc
Offset to source BITMAPINFO structure.
cbBmiSrc
Size of source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.
xMask
Horizontal pixel offset into mask bitmap.
yMask
Vertical pixel offset into mask bitmap.
iUsageMask
Value of the bmiColors member of the mask BITMAPINFO structure.
offBmiMask
Offset to mask BITMAPINFO structure.
cbBmiMask
Size of mask BITMAPINFO structure.
offBitsMask
Offset to mask bitmap bits.
cbBitsMask
Size of mask bitmap bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, MaskBlt, COLORREF, RGB


EMRMODIFYWORLDTRANSFORM

The EMRMODIFYWORLDTRANSFORM structure contains members for the ModifyWorldTransform enhanced metafile record.

typedef struct tagEMRMODIFYWORLDTRANSFORM {
  EMR   emr;
  XFORM xform;
  DWORD iMode;
   transformation
} EMRMODIFYWORLDTRANSFORM,
*PEMRMODIFYWORLDTRANSFORM;

Members

emr
Base structure for all record types.
xform
World-space to page-space transformation data.
iMode
Value specifying how the transformation data modifies the current world transformation. This member can be one of the following values: MWT_IDENTITY, MWT_LEFTMULTIPLY, or MWT_RIGHTMULTIPLY.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ModifyWorldTransform


EMROFFSETCLIPRGN

The EMROFFSETCLIPRGN structure contains members for the OffsetClipRgn enhanced metafile record.

typedef struct tagEMROFFSETCLIPRGN {
  EMR    emr;
  POINTL ptlOffset;
} EMROFFSETCLIPRGN, *PEMROFFSETCLIPRGN;

Members

emr
Base structure for all record types.
ptlOffset
Logical coordinates of offset.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, OffsetClipRgn


EMRPIXELFORMAT

The EMRPIXELFORMAT structure contains the members for the SetPixelFormat enhanced metafile record. The pixel format information in ENHMETAHEADER refers to this structure.

typedef struct tagEMRPIXELFORMAT {
  EMR         emr;
  PIXELFORMATDESCRIPTOR  pfd;
} EMRPIXELFORMAT, *PEMRPIXELFORMAT;

Members

emr
Base structure for all record types.
pfd
PIXELFORMATDESCRIPTOR structure, which describes the pixel format.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetPixelFormat, ENHMETAHEADER, PIXELFORMATDESCRIPTOR


EMRPLGBLT

The EMRPLGBLT structure contains members for the PlgBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

typedef struct tagEMRPLGBLT {
  EMR      emr;
  RECTL    rclBounds;
  POINTL   aptlDest[3];
  LONG    xSrc;
  LONG    ySrc;
  LONG     cxSrc;
  LONG     cySrc;
  XFORM   xformSrc;
  COLORREF crBkColorSrc;
  DWORD    iUsageSrc;
  DWORD    offBmiSrc;
  DWORD   cbBmiSrc;
  DWORD   offBitsSrc;
  DWORD   cbBitsSrc;
  LONG    xMask;
  LONG    yMask;
  DWORD   iUsageMask;
  DWORD   offBmiMask;
  DWORD   cbBmiMask;
  DWORD   offBitsMask;
  DWORD   cbBitsMask;
} EMRPLGBLT, *PEMRPLGBLT;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
aptlDest
Array of three points in logical space that identify 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.
xSrc
Logical x-coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y-coordinate of the upper-left corner of the source rectangle.
cxSrc
Logical width of the source.
cySrc
Logical height of the source.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context. To make a COLORREF value, use the RGB macro.
iUsageSrc
Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmiSrc
Offset to source BITMAPINFO structure.
cbBmiSrc
Size of source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.
xMask
Horizontal pixel offset into mask bitmap.
yMask
Vertical pixel offset into mask bitmap.
iUsageMask
Value of the bmiColors member of the mask BITMAPINFO structure.
offBmiMask
Offset to mask BITMAPINFO structure.
cbBmiMask
Size of mask BITMAPINFO structure.
offBitsMask
Offset to mask bitmap bits.
cbBitsMask
Size of mask bitmap bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, PlgBlt, COLORREF, RGB


EMRPOLYDRAW

The EMRPOLYDRAW structure contains members for the PolyDraw enhanced metafile record.

typedef struct tagEMRPOLYDRAW {
  EMR    emr;
  RECTL  rclBounds;
  DWORD  cptl;
  POINTL aptl[1];
  BYTE   abTypes[1];
} EMRPOLYDRAW, *PEMRPOLYDRAW;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cptl
Number of points.
aptl
Array of 32-bit points.
abTypes
Array of values that specifies how each point in the aptl array is used. This member can be one of the following values: PT_MOVETO, PT_LINETO, or PT_BEZIERTO. The PT_LINETO or PT_BEZIERTO value can be combined with the PT_CLOSEFIGURE value by using the bitwise-xOR operator.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, PolyDraw


EMRPOLYDRAW16

The EMRPOLYDRAW16 structure contains members for the PolyDraw enhanced metafile record.

typedef struct tagEMRPOLYDRAW16 {
  EMR    emr;
  RECTL  rclBounds;
  DWORD  cpts;
  POINTS apts[1];
  BYTE   abTypes[1];
} EMRPOLYDRAW16, *PEMRPOLYDRAW16;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cpts
Number of points.
apts
Array of 16-bit points.
abTypes
Array of values that specifies how each point in the apts array is used. This member can be one of the following values: PT_MOVETO, PT_LINETO, or PT_BEZIERTO. The PT_LINETO or PT_BEZIERTO value can be combined with the PT_CLOSEFIGURE value by using the bitwise-OR operator.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, PolyDraw


EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, EMRPOLYLINETO

The EMRPOLYLINE, EMRPOLYBEZIER, EMRPOLYGON, EMRPOLYBEZIERTO, and EMRPOLYLINETO structures contain members for the Polyline, PolyBezier, Polygon, PolyBezierTo, and PolylineTo enhanced metafile records.

typedef struct tagEMRPOLYLINE {
  EMR    emr;
  RECTL  rclBounds;
  DWORD  cptl;
  POINTL aptl[1];
} EMRPOLYLINE,     *PEMRPOLYLINE,
  EMRPOLYBEZIER,   *PEMRPOLYBEZIER,
  EMRPOLYGON,      *PEMRPOLYGON,
  EMRPOLYBEZIERTO, *PEMRPOLYBEZIERTO,
  EMRPOLYLINETO,   *PEMRPOLYLINETO;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cptl
Number of points array.
aptl
Array of 32-bit points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, EMRPOLYLINETO16

The EMRPOLYLINE16, EMRPOLYBEZIER16, EMRPOLYGON16, EMRPOLYBEZIERTO16, and EMRPOLYLINETO16 structures contain members for the Polyline, PolyBezier, Polygon, PolyBezierTo, and PolylineTo enhanced metafile records.

typedef struct tagEMRPOLYLINE {
  EMR    emr;
  RECTL  rclBounds;
  DWORD  cpts;
  POINTS apts[1];
} EMRPOLYLINE16,     *PEMRPOLYLINE16,
  EMRPOLYBEZIER16,   *PEMRPOLYBEZIER16,
  EMRPOLYGON16,      *PEMRPOLYGON16,
  EMRPOLYBEZIERTO16, *PEMRPOLYBEZIERTO16,
  EMRPOLYLINETO16,   *PEMRPOLYLINETO16;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
cpts
Number of points in the array.
apts
Array of 16-bit points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRPOLYPOLYLINE, EMRPOLYPOLYGON

The EMRPOLYPOLYLINE and EMRPOLYPOLYGON structures contain members for the PolyPolyline and PolyPolygon enhanced metafile records.

typedef struct tagEMRPOLYPOLYLINE {
  EMR     emr;
  RECTL   rclBounds;
  DWORD   nPolys;
  DWORD   cptl;
  DWORD   aPolyCounts[1];
  POINTL  aptl[1];
} EMRPOLYPOLYLINE, *PEMRPOLYPOLYLINE,
  EMRPOLYPOLYGON,  *PEMRPOLYPOLYGON;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
nPolys
Number of polys.
cptl
Total number of points in all polys.
aPolyCounts
Array of point counts for each poly.
aptl
Array of 32-bit points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRPOLYPOLYLINE16, EMRPOLYPOLYGON16

The EMRPOLYPOLYLINE16 and EMRPOLYPOLYGON16 structures contain members for the PolyPolyline and PolyPolygon enhanced metafile records.

typedef struct tagEMRPOLYPOLYLINE16 {
  EMR     emr;
  RECTL   rclBounds;
  DWORD   nPolys;
  DWORD   cpts;
  DWORD   aPolyCounts[1];
  POINTS  apts[1];
} EMRPOLYPOLYLINE16, *PEMRPOLYPOLYLINE16,
  EMRPOLYPOLYGON16,  *PEMRPOLYPOLYGON16;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
nPolys
Number of polys.
cpts
Total number of points in all polys.
aPolyCounts
Array of point counts for each poly.
apts
Array of 16-bit points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRPOLYTEXTOUTA, EMRPOLYTEXTOUTW

The EMRPOLYTEXTOUTA and EMRPOLYTEXTOUTW structures contain members for the PolyTextOut enhanced metafile record.

typedef struct tagEMRPOLYTEXTOUTA {
  EMR     emr;
  RECTL   rclBounds;
  DWORD   iGraphicsMode;
  FLOAT   exScale;
  FLOAT   eyScale;
  LONG    cStrings;
  EMRTEXT aemrtext[1];
} EMRPOLYTEXTOUTA, *PEMRPOLYTEXTOUTA,
  EMRPOLYTEXTOUTW, *PEMRPOLYTEXTOUTW;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
iGraphicsMode
Current graphics mode. This member can be either the GM_COMPATIBLE or GM_ADVANCED value.
exScale
X-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.
eyScale
Y-scaling factor from page units to .01mm units if the graphics mode is the GM_COMPATIBLE value.
cStrings
Number of strings.
aemrtext
EMRTEXT structure, which is followed by the string and the intercharacter spacing array.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRRESIZEPALETTE

The EMRRESIZEPALETTE structure contains members for the ResizePalette enhanced metafile record.

typedef struct tagEMRRESIZEPALETTE {
  EMR   emr;
  DWORD ihPal;
  DWORD cEntries;
} EMRRESIZEPALETTE, *PEMRRESIZEPALETTE;

Members

emr
Base structure for all record types.
ihPal
Index of the palette in the handle table.
cEntries
Number of entries in palette after resizing.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ResizePalette


EMRRESTOREDC

The EMRRESTOREDC structure contains members for the RestoreDC enhanced metafile record.

typedef struct tagEMRRESTOREDC {
  EMR  emr;
  LONG iRelative;
} EMRRESTOREDC, *PEMRRESTOREDC;

Members

emr
Base structure for all record types.
iRelative
Relative instance to restore.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, RestoreDC


EMRROUNDRECT

The EMRROUNDRECT structure contains members for the RoundRect enhanced metafile record.

typedef struct tagEMRROUNDRECT {
  EMR   emr;
  RECTL rclBox;
  SIZEL szlCorner;
} EMRROUNDRECT, *PEMRROUNDRECT;

Members

emr
Base structure for all record types.
rclBox
Bounding rectangle.
szlCorner
Width and height of the ellipse used to draw rounded corners.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, RoundRect


EMRSCALEVIEWPORTEXTEX, EMRSCALEWINDOWEXTEX

The EMRSCALEVIEWPORTEXTEX and EMRSCALEWINDOWEXTEX structures contain members for the ScaleViewportExtEx and ScaleWindowExtEx enhanced metafile records.

typedef struct tagEMRSCALEVIEWPORTEXTEX {
  EMR  emr;
  LONG xNum;
  LONG xDenom;
  LONG yNum;
  LONG yDenom;
} EMRSCALEVIEWPORTEXTEX, *PEMRSCALEVIEWPORTEXTEX,
  EMRSCALEWINDOWEXTEX,   *PEMRSCALEWINDOWEXTEX;

Members

emr
Base structure for all record types.
xNum
Horizontal multiplicand.
xDenom
Horizontal divisor.
yNum
Vertical multiplicand.
yDenom
Vertical divisor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRSETCOLORSPACE, EMRSELECTCOLORSPACE, EMRDELETECOLORSPACE

The EMRSETCOLORSPACE, EMRSELECTCOLORSPACE, and EMRDELETECOLORSPACE structures contain members for the SetColorSpace and DeleteColorSpace enhanced metafile records.

typedef struct tagEMRSETCOLORSPACE {
  EMR     emr;
  DWORD   ihCS;
} EMRSETCOLORSPACE, *PEMRSETCOLORSPACE,
  EMRSELECTCOLORSPACE, *PEMRSELECTCOLORSPACE,
  EMRDELETECOLORSPACE, *PEMRDELETECOLORSPACE;

Members

emr
Base structure for all record types.
ihCS
Color space handle index.

Remarks

There is no function that generates an enhanced metafile record with the EMRSELECTCOLORSPACE structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRSELECTOBJECT, EMRDELETEOBJECT

The EMRSELECTOBJECT and EMRDELETEOBJECT structures contain members for the SelectObject and DeleteObject enhanced metafile records.

typedef struct tagEMRSELECTOBJECT {
  EMR   emr;
  DWORD ihObject;
} EMRSELECTOBJECT, *PEMRSELECTOBJECT,
  EMRDELETEOBJECT, *PEMRDELETEOBJECT;

Members

emr
Base structure for all record types.
ihObject
Index of an object in the handle table.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRSELECTPALETTE

The EMRSELECTPALETTE structure contains members for the SelectPalette enhanced metafile record. Note that the bForceBackground parameter in SelectPalette is always recorded as TRUE, which causes the palette to be realized as a background palette.

typedef struct tagEMRSELECTPALETTE {
  EMR   emr;
  DWORD ihPal;
} EMRSELECTPALETTE, *PEMRSELECTPALETTE;

Members

emr
Base structure for all record types.
ihPal
Index to logical palette in the handle table.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SelectPalette


EMRSETARCDIRECTION

The EMRSETARCDIRECTION structure contains members for the SetArcDirection enhanced metafile record.

typedef struct tagEMRSETARCDIRECTION {
  EMR   emr;
  DWORD iArcDirection;
} EMRSETARCDIRECTION, *PEMRSETARCDIRECTION;

Members

emr
Base structure for all record types.
iArcDirection
Arc direction. This member can be either the AD_CLOCKWISE or AD_COUNTERCLOCKWISE value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, Arc, SetArcDirection


EMRSETBKCOLOR, EMRSETTEXTCOLOR

The EMRSETBKCOLOR and EMRSETTEXTCOLOR structures contain members for the SetBkColor and SetTextColor enhanced metafile records.

typedef struct tagEMRSETTEXTCOLOR {
  EMR      emr;
  COLORREF crColor;
} EMRSETBKCOLOR,   *PEMRSETBKCOLOR,
  EMRSETTEXTCOLOR, *PEMRSETTEXTCOLOR;

Members

emr
Base structure for all record types.
crColor
Color value.To make a COLORREF value, use the RGB macro.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, , COLORREF, RGB


EMRSETCOLORADJUSTMENT

The EMRSETCOLORADJUSTMENT structure contains members for the SetColorAdjustment enhanced metafile record.

typedef struct tagEMRSETCOLORADJUSTMENT {
  EMR  emr;
  COLORADJUSTMENT ColorAdjustment;
} EMRSETCOLORADJUSTMENT, *PEMRSETCOLORADJUSTMENT;

Members

emr
Base structure for all record types.
ColorAdjustment
COLORADJUSTMENT structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetColorAdjustment


EMRSETDIBITSTODEVICE

The EMRSETDIBITSTODEVICE structure contains members for the SetDIBitsToDevice enhanced metafile record.

typedef struct tagEMRSETDIBITSTODEVICE {
  EMR   emr;
  RECTL rclBounds;
  LONG  xDest;
  LONG  yDest;
  LONG  xSrc;
  LONG  ySrc;
  LONG  cxSrc;
  LONG  cySrc;
  DWORD offBmiSrc;
  DWORD cbBmiSrc;
  DWORD offBitsSrc;
  DWORD cbBitsSrc;
  DWORD iUsageSrc;
  DWORD iStartScan;
  DWORD cScans;
} EMRSETDIBITSTODEVICE, *PEMRSETDIBITSTODEVICE;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
xDest
Logical x-coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y-coordinate of the upper-left corner of the destination rectangle.
xSrc
Logical x-coordinate of the lower-left corner of the source device-independent bitmap (DIB).
ySrc
Logical y-coordinate of the lower-left corner of the source DIB.
cxSrc
Width of the source rectangle.
cySrc
Height of the source rectangle.
offBmiSrc
Offset to the source BITMAPINFO structure.
cbBmiSrc
Size of the source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.
iUsageSrc
Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
iStartScan
First scan line in the array.
cScans
Number of scan lines.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, SetDIBitsToDevice


EMRSETICMPROFILE

The EMRSETICMPROFILE structure contains members for the SetICMProfile enhanced metafile record.

typedef struct tagEMRSETICMPROFILE {
  EMR     emr;
  DWORD   dwFlags;
  DWORD   cbName;
  DWORD   cbData;
  BYTE    Data[1];
} EMRSETICMPROFILE, *PEMRSETICMPROFILE,
  EMRSETICMPROFILEA, *PEMRSETICMPROFILEA,
  EMRSETICMPROFILEW, *PEMRSETICMPROFILEW;

Members

emr
Base structure for all record types.
dwFlags
Profile Flags.
cbName
Size of the desired profile name.
cbData
Size of profile data, if attached.
Data[1]
Array size is cbName and cbData.

Remarks

This structure is to be used during metafile playback.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, Metafiles, SetICMProfile


EMRSETMAPPERFLAGS

The EMRSETMAPPERFLAGS structure contains members for the SetMapperFlags enhanced metafile record.

typedef struct tagEMRSETMAPPERFLAGS {
  EMR   emr;
  DWORD dwFlags;
} EMRSETMAPPERFLAGS, *PEMRSETMAPPERFLAGS;

Members

emr
Base structure for all record types.
dwFlags
Font mapper flag.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetMapperFlags


EMRSETMITERLIMIT

The EMRSETMITERLIMIT structure contains members for the SetMiterLimit enhanced metafile record.

typedef struct tagEMRSETMITERLIMIT {
  EMR   emr;
  FLOAT eMiterLimit;
} EMRSETMITERLIMIT, *PEMRSETMITERLIMIT;

Members

emr
Base structure for all record types.
eMiterLimit
New miter limit.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetMiterLimit


EMRSETPALETTEENTRIES

The EMRSETPALETTEENTRIES structure contains members for the SetPaletteEntries enhanced metafile record.

typedef struct tagEMRSETPALETTEENTRIES {
  EMR          emr;
  DWORD        ihPal;
  DWORD        iStart;
  DWORD        cEntries;
  PALETTEENTRY aPalEntries[1];
} EMRSETPALETTEENTRIES, *PEMRSETPALETTEENTRIES;

Members

emr
Base structure for all record types.
ihPal
Palette handle index.
iStart
Index of first entry to set.
cEntries
Number of entries.
aPalEntries
Array of PALETTEENTRY structures. Note that peFlags members in the structures do not contain any flags.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, PALETTEENTRY, SetPaletteEntries


EMRSETPIXELV

The EMRSETPIXELV structure contains members for the SetPixelV enhanced metafile record. When an enhanced metafile is created, calls to SetPixel are also recorded in this record.

typedef struct tagEMRSETPIXELV {
  EMR     emr;
  POINTL  ptlPixel;
  COLORREF crColor;
} EMRSETPIXELV, *PEMRSETPIXELV;

Members

emr
Base structure for all record types.
ptlPixel
Logical coordinates of pixel.
crColor
Color value.To make a COLORREF value, use the RGB macro.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetPixelV, SetPixel , COLORREF, RGB


EMRSETVIEWPORTEXTEX, EMRSETWINDOWEXTEX

The EMRSETVIEWPORTEXTEX and EMRSETWINDOWEXTEX structures contains members for the SetViewportExtEx and SetWindowExtEx enhanced metafile records.

typedef struct tagEMRSETVIEWPORTEXTEX {
  EMR   emr;
  SIZEL szlExtent;
} EMRSETVIEWPORTEXTEX, *PEMRSETVIEWPORTEXTEX,
  EMRSETWINDOWEXTEX,   *PEMRSETWINDOWEXTEX;

Members

emr
Base structure for all record types.
szlExtent
Horizontal and vertical extents. For SetViewportExtEx, the extents are in device units, and for SetWindowExtEx, the extents are in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, EMRSETBRUSHORGEX

The EMRSETVIEWPORTORGEX, EMRSETWINDOWORGEX, and EMRSETBRUSHORGEX structures contain members for the SetViewportOrgEx, SetWindowOrgEx, and SetBrushOrgEx enhanced metafile records.

typedef struct tagEMRSETVIEWPORTORGEX {
  EMR    emr;
  POINTL ptlOrigin;
} EMRSETVIEWPORTORGEX, *PEMRSETVIEWPORTORGEX,
  EMRSETWINDOWORGEX,   *PEMRSETWINDOWORGEX,
  EMRSETBRUSHORGEX,    *PEMRSETBRUSHORGEX;

Members

emr
Base structure for all record types.
ptlOrigin
Coordinate of origin.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetBrushOrgEx, SetViewportOrgEx, SetWindowOrgEx


EMRSETWORLDTRANSFORM

The EMRSETWORLDTRANSFORM structure contains members for the SetWorldTransform enhanced metafile record.

typedef struct tagEMRSETWORLDTRANSFORM {
  EMR   emr;
  XFORM xform;
} EMRSETWORLDTRANSFORM, *PEMRSETWORLDTRANSFORM;

Members

emr
Base structure for all record types.
xform
World-space to page-space transformation data.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SetWorldTransform


EMRSTRETCHBLT

The EMRSTRETCHBLT structure contains members for the StretchBlt enhanced metafile record. Note that graphics device interface (GDI) converts the device-dependent bitmap into a device-independent bitmap (DIB) before storing it in the metafile record.

typedef struct tagEMRSTRETCHBLT {
  EMR      emr;
  RECTL    rclBounds;
  LONG     xDest;
  LONG     yDest;
  LONG     cxDest;
  LONG     cyDest;
  DWORD    dwRop;
  LONG     xSrc;
  LONG     ySrc;
  XFORM    xformSrc;
  COLORREF crBkColorSrc;
  DWORD    iUsageSrc;
  DWORD    offBmiSrc;
  DWORD    cbBmiSrc;
  DWORD    offBitsSrc;
  DWORD    cbBitsSrc;
  LONG     cxSrc;
  LONG     cySrc;
} EMRSTRETCHBLT, *PEMRSTRETCHBLT;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
xDest
Logical x-coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y-coordinate of the upper-left corner of the destination rectangle.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.
dwRop
Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.
xSrc
Logical x-coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y-coordinate of the upper-left corner of the source rectangle.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context.To make a COLORREF value, use the RGB macro.
iUsageSrc
Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
offBmiSrc
Offset to the source BITMAPINFO structure.
cbBmiSrc
Size of the source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.
cxSrc
Width of the source rectangle.
cySrc
Height of the source rectangle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, COLORREF, RGB, StretchBlt


EMRSTRETCHDIBITS

The EMRSTRETCHDIBITS structure contains members for the StretchDIBits enhanced metafile record.

typedef struct tagEMRSTRETCHDIBITS {
  EMR   emr;
  RECTL rclBounds;
  LONG  xDest;
  LONG  yDest;
  LONG  xSrc;
  LONG  ySrc;
  LONG  cxSrc;
  LONG  cySrc;
  DWORD offBmiSrc;
  DWORD cbBmiSrc;
  DWORD offBitsSrc;
  DWORD cbBitsSrc;
  DWORD iUsageSrc;
  DWORD dwRop;
  LONG  cxDest;
  LONG  cyDest;
} EMRSTRETCHDIBITS, *PEMRSTRETCHDIBITS;

Members

emr
Base structure for all record types.
rclBounds
Bounding rectangle, in device units.
xDest
Logical x-coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y-coordinate of the upper-left corner of the destination rectangle.
xSrc
Logical x-coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y-coordinate of the upper-left corner of the source rectangle.
cxSrc
Width of the source rectangle.
cySrc
Height of the source rectangle.
offBmiSrc
Offset to the source BITMAPINFO structure.
cbBmiSrc
Size of the source BITMAPINFO structure.
offBitsSrc
Offset to source bitmap bits.
cbBitsSrc
Size of source bitmap bits.
iUsageSrc
Value of the bmiColors member of the BITMAPINFO structure. The iUsageSrc member can be either the DIB_PAL_COLORS or DIB_RGB_COLORS value.
dwRop
Raster-operation code. These codes define how the color data of the source rectangle is to be combined with the color data of the destination rectangle to achieve the final color.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, BITMAPINFO, StretchDIBits


EMRTEXT

The EMRTEXT structure contains members for text output.

typedef struct tagEMRTEXT {
  POINTL ptlReference;
  DWORD  nChars;
  DWORD  offString;
  DWORD  fOptions;
  RECTL  rcl;
  DWORD  offDx;
} EMRTEXT, *PEMRTEXT;

Members

ptlReference
Logical coordinates of the reference point used to position the string.
nChars
Number of characters in string.
offString
Offset to string.
fOptions
Value specifying how to use the application-defined rectangle. This member can be a combination of the ETO_CLIPPED and ETO_OPAQUE values.
rcl
Optional clipping and/or opaquing rectangle.
offDx
Offset to intercharacter spacing array.

Remarks

The EMRTEXT structure is used as a member in the EMREXTTEXTOUT and EMRPOLYTEXTOUT structures.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


EMRTRANSPARENTBLT

The EMRTRANSPARENTBLT structure contains members for the TransparentBLT enhanced metafile record.

typedef struct tagEMRTRANSPARENTBLT {
  EMR     emr;
  RECTL   rclBounds;
  LONG    xDest;
  LONG    yDest;
  LONG    cxDest;
  LONG    cyDest;
  DWORD   dwRop;
  LONG    xSrc;
  LONG    ySrc;
  XFORM   xformSrc;
  COLORREF crBkColorSrc;
  DWORD   iUsageSrc;
  DWORD   offBmiSrc;
  DWORD   cbBmiSrc;
  DWORD   offBitsSrc;
  DWORD   cbBitsSrc;
  LONG    cxSrc;
  LONG    cySrc;
} EMREMRTRANSPARENTBLT, *PEMREMRTRANSPARENTBLT;

Members

emr
Base structure for all record types.
rclBounds
Inclusive bounds, in device units.
xDest
Logical x coordinate of the upper-left corner of the destination rectangle.
yDest
Logical y coordinate of the upper-left corner of the destination rectangle.
cxDest
Logical width of the destination rectangle.
cyDest
Logical height of the destination rectangle.
dwRop
Stores the transparent color.
xSrc
Logical x coordinate of the upper-left corner of the source rectangle.
ySrc
Logical y coordinate of the upper-left corner of the source rectangle.
xformSrc
World-space to page-space transformation of the source device context.
crBkColorSrc
Background color (the RGB value) of the source device context. To make a COLORREF value, use the RGB macro.
iUsageSrc
Source bitmap information color table usage (DIB_RGB_COLORS).
offBmiSrc
Offset to the source BITMAPINFO structure.
cbBmiSrc
Size of the source BITMAPINFO structure.
offBitsSrc
Offset to the source bitmap bits.
cbBitsSrc
Size of the source bitmap bits.
cxSrc
Width of the source rectangle.
cySrc
Height of the source rectangle.

Remarks

This structure is to be used during metafile playback.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, Metafiles, TransparentBLT, BITMAPINFO, COLORREF, RGB


Enhanced Metafile Records with No Parameters

Contains data for the AbortPath, BeginPath, EndPath, CloseFigure, FlattenPath, WidenPath, SetMetaRgn, SaveDC, and RealizePalette enhanced metafile records.

typedef struct tagABORTPATH {
  EMR emr;
} EMRABORTPATH,      *PEMRABORTPATH,
  EMRBEGINPATH,      *PEMRBEGINPATH,
  EMRENDPATH,        *PEMRENDPATH,
  EMRCLOSEFIGURE,    *PEMRCLOSEFIGURE,
  EMRFLATTENPATH,    *PEMRFLATTENPATH,
  EMRWIDENPATH,      *PEMRWIDENPATH,
  EMRSETMETARGN,     *PEMRSETMETARGN,
  EMRSAVEDC,         *PEMRSAVEDC,
  EMRREALIZEPALETTE, *PEMRREALIZEPALETTE;

Members

emr
Base structure for all record types.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


Enhanced Metafile Records with One Parameter

Contains parameters for the SelectClipPath, SetBkMode, SetMapMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign, SetICMMode, and SetLayout enhanced metafile records.

typedef struct tagEMRSELECTCLIPPATH {
  EMR   emr;
  DWORD iMode;
} EMRSELECTCLIPPATH,    *PEMRSELECTCLIPPATH,
  EMRSETBKMODE,         *PEMRSETBKMODE,
  EMRSETMAPMODE,        *PEMRSETMAPMODE,
  EMRSETPOLYFILLMODE,   *PEMRSETPOLYFILLMODE,
  EMRSETROP2,           *PEMRSETROP2,
  EMRSETSTRETCHBLTMODE, *PEMRSETSTRETCHBLTMODE,
  EMRSETTEXTALIGN,      *PEMRSETTEXTALIGN,
  EMRSETICMMODE,        *PEMRSETICMMODE,
#if(WINVER >= 0x0500)
  EMRSETLAYOUT,         *PEMRSETLAYOUT
#endif /* WINVER >= 0x0500 */

Members

emr
Base structure for all record types.
iMode
Value and meaning that varies depending on the function contained in the enhanced metafile record. For a description of this member, see the documentation of the functions contained in this record.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, SelectClipPath, SetBkMode, SetMapMode, SetPolyFillMode, SetROP2, SetStretchBltMode, SetTextAlign


ENHMETAHEADER

The ENHMETAHEADER structure contains enhanced-metafile data such as the dimensions of the picture stored in the enhanced metafile, the count of records in the enhanced metafile, the resolution of the device on which the picture was created, and so on.

This structure is always the first record in an enhanced metafile.

typedef struct tagENHMETAHEADER {
  DWORD iType;
  DWORD nSize;
  RECTL rclBounds;
  RECTL rclFrame;
  DWORD dSignature;
  DWORD nVersion;
  DWORD nBytes;
  DWORD nRecords;
  WORD  nHandles;
  WORD  sReserved;
  DWORD nDescription;
  DWORD offDescription;
  DWORD nPalEntries;
  SIZEL szlDevice;
  SIZEL szlMillimeters;
#if (WINVER >= 0x0400)
  DWORD cbPixelFormat;
  DWORD offPixelFormat;
  DWORD bOpenGL;
#endif /* WINVER >= 0x0400 */
#if (WINVER >= 0x0500)
  SIZEL szlMicrometers;
#endif /* WINVER >= 0x0500 */
} ENHMETAHEADER, *PENHMETAHEADER;

Members

iType
Specifies the record type. This member must specify the value assigned to the EMR_HEADER constant.
nSize
Specifies the structure size, in bytes.
rclBounds
Specifies the dimensions, in device units, of the smallest rectangle that can be drawn around the picture stored in the metafile. This rectangle is supplied by graphics device interface (GDI). Its dimensions include the right and bottom edges.
rclFrame
Specifies the dimensions, in .01 millimeter units, of a rectangle that surrounds the picture stored in the metafile. This rectangle must be supplied by the application that creates the metafile. Its dimensions include the right and bottom edges.
dSignature
Specifies a double word signature. This member must specify the value assigned to the ENHMETA_SIGNATURE constant.
nVersion
Specifies the metafile version. The current version value is 0x10000.
nBytes
Specifies the size of the enhanced metafile, in bytes.
nRecords
Specifies the number of records in the enhanced metafile.
nHandles
Specifies the number of handles in the enhanced-metafile handle table. (Index zero in this table is reserved.)
sReserved
Reserved; must be zero.
nDescription
Specifies the number of characters in the array that contains the description of the enhanced metafile's contents. This member should be set to zero if the enhanced metafile does not contain a description string.
offDescription
Specifies the offset from the beginning of the ENHMETAHEADER structure to the array that contains the description of the enhanced metafile's contents. This member should be set to zero if the enhanced metafile does not contain a description string.
nPalEntries
Specifies the number of entries in the enhanced metafile's palette.
szlDevice
Specifies the resolution of the reference device, in pixels.
szlMillimeters
Specifies the resolution of the reference device, in millimeters.
cbPixelFormat
Windows 95/98, Windows NT4.0 and later: Specifies the size of the last recorded pixel format in a metafile. If a pixel format is set in a reference DC at the start of recording, cbPixelFormat is set to the size of the PIXELFORMATDESCRIPTOR. When no pixel format is set when a metafile is recorded, this member is set to zero. If more than a single pixel format is set, the header points to the last pixel format.
offPixelFormat
Windows 95/98, Windows NT4.0 and later: Specifies the offset of pixel format used when recording a metafile. If a pixel format is set in a reference DC at the start of recording or during recording, offPixelFormat is set to the offset of the PIXELFORMATDESCRIPTOR in the metafile. If no pixel format is set when a metafile is recorded, this member is set to zero. If more than a single pixel format is set, the header points to the last pixel format.
bOpenGL
Windows 95/98, Windows NT4.0 and later: Specifies whether any OpenGL records are present in a metafile. bOpenGL is a simple Boolean flag that you can use to determine whether an enhanced metafile requires OpenGL handling. When a metafile contains OpenGL records, bOpenGL is TRUE; otherwise it is FALSE.
szlMicrometers
Windows 98/Me, Windows 2000 or later: Size of the reference device in micrometers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ENHMETARECORD


ENHMETARECORD

The ENHMETARECORD structure contains data that describes a graphics device interface (GDI) function used to create part of a picture in an enhanced-format metafile.

typedef struct tagENHMETARECORD {
  DWORD iType;
  DWORD nSize;
  DWORD dParm[1];
} ENHMETARECORD, *PENHMETARECORD;

Members

iType
Specifies the record type.
nSize
Specifies the size of the record, in bytes.
dParm
Specifies an array of parameters passed to the GDI function identified by the record.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, ENHMETAHEADER


HANDLETABLE

The HANDLETABLE structure is an array of handles, each of which identifies a graphics device interface (GDI) object.

typedef struct tagHANDLETABLE {
  HGDIOBJ objectHandle[1];
} HANDLETABLE, *PHANDLETABLE;

Members

objectHandle
Contains an array of handles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, EnhMetaFileProc, EnumMetaFileProc


METAHEADER

The METAHEADER structure contains information about a Windows-format metafile.

typedef struct tagMETAHEADER {
  WORD  mtType;
  WORD  mtHeaderSize;
  WORD  mtVersion;
  DWORD mtSize;
  WORD  mtNoObjects;
  DWORD mtMaxRecord;
  WORD  mtNoParameters;
} METAHEADER, *PMETAHEADER;

Members

mtType
Specifies whether the metafile is in memory or recorded in a disk file. This member can be one of the following values.
Value | Meaning
1 | Metafile is in memory.
2 | Metafile is in a disk file.

mtHeaderSize
Specifies the size, in words, of the metafile header.
mtVersion
Specifies the system version number. The version number for metafiles that support device-independent bitmaps (DIBs) is 0x0300. Otherwise, the version number is 0x0100.
mtSize
Specifies the size, in words, of the file.
mtNoObjects
Specifies the maximum number of objects that exist in the metafile at the same time.
mtMaxRecord
Specifies the size, in words, of the largest record in the metafile.
mtNoParameters
Reserved.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, METARECORD


METARECORD

The METARECORD structure contains a Windows-format metafile record.

typedef struct tagMETARECORD {
  DWORD rdSize;
  WORD  rdFunction;
  WORD  rdParm[1];
} METARECORD, *PMETARECORD;

Members

rdSize
Specifies the size, in words, of the record.
rdFunction
Specifies the function number.
rdParm
Specifies an array of words containing the function parameters, in reverse of the order they are passed to the function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, METAHEADER


POINTL

The POINTL structure contains the coordinates of a point.

typedef struct _POINTL {
  LONG x;
  LONG y;
} POINTL, *PPOINTL;

Members

x
Specifies the horizontal (x) coordinate of the point.
y
Specifies the vertical (y) coordinate of the point.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures


RECTL

The RECTL structure defines the coordinates of the upper-left and lower-right corners of a rectangle.

typedef struct _RECTL {
  LONG left;
  LONG top;
  LONG right;
  LONG bottom;
} RECTL, *PRECTL;

Members

left
Specifies the x-coordinate of the upper-left corner of the rectangle.
top
Specifies the y-coordinate of the upper-left corner of the rectangle.
right
Specifies the x-coordinate of the lower-right corner of the rectangle.
bottom
Specifies the y-coordinate of the lower-right corner of the rectangle.

Remarks

When RECTL is passed to the FillRect function, the rectangle is filled up to, but not including, the right column and bottom row of pixels. This structure is identical to the RECT structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Metafiles Overview, Metafile Structures, FillRect, RECT, SMALL_RECT


Multiple Display Monitors

Multiple Display Monitors is a set of related features that allow applications to make use of multiple display devices at the same time. There are two ways that multiple monitors may be used: as one large desktop or as a number of independent displays. When used as one large desktop, the monitors create more screen space for applications. This is useful whenever you need to maximize your onscreen workspace, and is especially useful in desktop publishing, Web development, or video editing. When used as independent displays, the monitors can be used for playing games, debugging fullscreen applications, teaching, or making presentations.

This chapter covers the following topics:

  • About Multiple Display Monitors
  • Using Multiple Display Monitors
  • Multiple Display Monitors Reference


About Multiple Display Monitors

When multiple monitors are part of the desktop, objects can travel seamlessly between monitors. That is, you can drag windows or shortcuts from one monitor to another, and you can size windows to cover more than one monitor. Also, if one monitor is installed above another, a cursor that leaves the bottom of the upper monitor appears at the top of the lower monitor.

Typically, a user arranges the monitors in the system to reflect the arrangement of the physical display units; for example, side-by-side or one-on-top-of-the-other. The user does this with the Monitors tab—which replaces the Settings tab—in the Display Properties dialog box through Control Panel. The monitors must form one contiguous region, that is, each monitor touches another monitor on at least part of one edge.

When a window is moved or resized, some part of the caption is always visible so the user can move and resize the window using the mouse. Cursor movement is restricted to the area of the monitors, so it is always visible. Shell icons are positioned on the same monitor as the taskbar, and the taskbar can be on any monitor, see Multiple Monitor Considerations for Older Programs.

A multiple monitor system affects certain key combinations. The ALT+PRINTSCRN key combination takes a snapshot of the foreground window, as always. However, the PRINTSCRN key takes a snapshot of the monitor that has the mouse. The CTRL+PRINTSCRN key combination takes a snapshot of the entire virtual screen, see The Virtual Screen.

The support for multiple monitors does not affect the performance of applications when running in a single display environment. That is, when running on a single display system, no additional overhead will be present in the high-performance graphics operations code. However, in a multiple monitor system, performance is slightly affected if an application runs only on one of the graphics devices. Also, performance may be greatly affected if an application spans multiple displays, especially for graphics-intensive operations.

Full-screen is a feature provided by the operating system that allows a user to toggle an application into a special state where the application can access VGA graphics hardware directly. This is a key feature for games and other graphics-focused applications that require high performance. Also, it is often used by developers for text editing since it enables very fast text scrolling.

In a multiple monitor environment, only one graphics device can be VGA compatible. This is a limitation of computer hardware which requires that only one device respond to any hardware address. Because the VGA hardware compatibility standard requires specific hardware addresses, only one VGA graphics device can be present in a machine and only this device can physically respond to VGA addresses. Thus, applications that require going full screen will only run on the particular device that supports VGA hardware compatibility.


The Virtual Screen

The bounding rectangle of all the monitors is the virtual screen. The desktop covers the virtual screen instead of a single monitor. The following illustration shows a possible arrangement of three monitors.

The primary monitor contains the origin (0,0). This is for compatibility with existing applications that expect a monitor with an origin. However, the primary monitor does not have to be in the upper left of the virtual screen. In Figure 1, it is near the center. When the primary monitor is not in the upper left of the virtual screen, parts of the virtual screen have negative coordinates. Because the arrangement of monitors is set by the user, all applications should be designed to work with negative coordinates. For more information, see Multiple Monitor Considerations for Older Programs. For Windows 98, the primary monitor is the same as the VGA/Boot display. For Windows 2000, the primary monitor can be any monitor.

The coordinates of the virtual screen are represented by a signed 16-bit value because of the 16-bit values contained in many existing messages. Thus, the bounds of the virtual screen are:

SHORT_MIN    <= rcVirtualScreen.left   <= SHORT_MAX - 1
SHORT_MIN +1 <= rcVirtualScreen.right  <= SHORT_MAX
SHORT_MIN    <= rcVirtualScreen.top    <= SHORT_MAX - 1
SHORT_MIN +1 <= rcVirtualScreen.bottom <= SHORT_MAX


HMONITOR and the Device Context

Each physical display is represented by a monitor handle of type HMONITOR. A valid HMONITOR is guaranteed to be non-NULL. A physical display has the same HMONITOR as long as it is part of the desktop. When a WM_DISPLAYCHANGE message is sent, any monitor may be removed from the desktop—and thus its HMONITOR becomes invalid—or has its settings changed. Therefore, an application should check whether all HMONITORS are valid when this message is sent.

Any function that returns a display device context (DC) normally returns a DC for the primary monitor. To obtain the DC for another monitor, use the EnumDisplayMonitors function. Or, you can use the device name from the GetMonitorInfo function to create a DC with CreateDC. However, if the function, such as GetWindowDC or BeginPaint, gets a DC for a window that spans more than one display, the DC will also span the two displays.


Enumeration and Display Control

To enumerate all the devices on the computer, call the EnumDisplayDevices function. The information that is returned also indicates which monitor is part of the desktop.

To enumerate the devices on the desktop that intersect a clipping region, call EnumDisplayMonitors. This returns the HMONITOR handle for each monitor, which is used with GetMonitorInfo. To enumerate all the devices in the virtual screen, use EnumDisplayMonitors. as shown in the following code:

EnumDisplayMonitors(NULL, NULL, MyInfoEnumProc, 0);

To get information about a display device, use EnumDisplaySettings or EnumDisplaySettingsEx.

The ChangeDisplaySettingsEx function is used to control the display devices on the computer. It can modify the configuration of the devices, such as specifying the position of a monitor on the virtual desktop and changing the bit depth of any display. Typically, an application does not use this function. To add a display monitor to a multiple-monitor system programmatically, set DEVMODE.dmFields to DM_POSITION and specify a position (using DEVMODE.dmPosition) for the monitor you are adding that is adjacent to at least one pixel of the display area of an existing monitor. To detach the monitor, set DEVMODE.dmFields to DM_POSITION and set DEVMODE.dmPelsWidth and DEVMODE.dmPelsHeight to zero.

For each display device, the application can save information in the registry that describes the configuration parameters for the device, as well as location parameters. The application can also determine which displays are part of the desktop, and which are not, through the DISPLAY_DEVICE_ATTACHED_TO_DESKTOP flag in the DISPLAY_DEVICE structure. Once all the configuration information is stored in the registry, the application can call ChangeDisplaySettingsEx again to dynamically change the settings, with no restart required.


Multiple Monitor System Metrics

The GetSystemMetrics function returns values for the primary monitor, except for SM_CXMAXTRACK and SM_CYMAXTRACK, which refer to the entire desktop. The following metrics are the same for all device drivers: SM_CXCURSOR, SM_CYCURSOR, SM_CXICON, SMCYICON. The following display capabilities are the same for all monitors: LOGPIXELSX, LOGPIXELSY, DESTOPHORZRES, DESKTOPVERTRES.

GetSystemMetrics also has constants that refer only to a Multiple Monitor system. SM_XVIRTUALSCREEN and SM_YVIRTUALSCREEN identify the upper-left corner of the virtual screen, SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN are the vertical and horizontal measurements of the virtual screen, SM_CMONITORS is the number of monitors attached to the desktop, and SM_SAMEDISPLAYFORMAT indicates whether all the monitors on the desktop have the same color format.

To get information about a single display monitor or all of the display monitors in a desktop, use EnumDisplayMonitors.The rectangle of the desktop window returned by GetWindowRect or GetClientRect is always equal to the rectangle of the primary monitor, for compatibility with existing applications. Thus, the result of

GetWindowRect(GetDesktopWindow(), &rc);

will be:

rc.left = 0;
rc.top = 0;
rc.right = GetSystemMetrics (SM_CXSCREEN);
rc.bottom = GetSystemMetrics (SM_CYSCREEN);

To change the work area of a monitor, call SystemParametersInfo with SPI_SETWORKAREA and pvParam pointing to a RECT structure that is on the desired monitor. If pvParam is NULL, the work area of the primary monitor is modified. Using SPI_GETWORKAREA always returns the work area of the primary monitor. To get the work area of a monitor other than the primary monitor, call GetMonitorInfo.


Using Multiple Monitors as Independent Displays

When using multiple monitors as independent displays, the desktop contains one display or set of displays. This set of displays always includes the primary monitor and behaves as mentioned in the other sections of this topic. An application can use any other monitor as an independent display.

The window manager knows nothing about the independent displays. They are completely controlled by the application, and no window manager functions are available to the application (all window manager calls automatically go to the primary display). Each independent display has its own origin and horizontal and vertical coordinates, and is accessed through the GDI functions such as CreateDC or the DirectX functions such as DirectDrawCreate.

To locate the independent displays, call EnumDisplayDevices and look for the displays that do not have DISPLAY_DEVICE_ATTACHED_TO_DESKTOP flag in the DISPLAY_DEVICE structure.

An application can open a display by calling

hdc = CreateDC(lpszDisplayName, NULL, NULL, lpDevMode);

In this call, the lpszDisplayName parameter is one of the device names returned by EnumDisplayDevices and lpDevMode is a description of the graphics mode for this device. The resulting hdc can be used to perform any graphics operation to the device.


Colors on Multiple Display Monitors

Each monitor can have its own color depth. The system automatically adjusts colors as windows move across monitors with different color depths. In general, this produces good results. However, this is not always optimal. To take advantage of the color capabilities of different monitors, see the Painting on Multiple Display Monitors section that follows.

To determine if all monitors have the same color format, call GetSystemMetrics with SM_SAMEDISPLAYFORMAT.

If the primary monitor is palettized, SelectPalette and RealizePalette work the same as before, but across all monitors. In addition, the palettes of all palettized devices are synchronized. If the primary monitor is not palettized, SelectPalette and RealizePalette will select the palette into the background and palettized devices will not be synchronized.


Painting on Multiple Display Monitors

The system automatically handles painting into a device context (DC) that spans more than one monitor, even when the monitors have different color depths. Usually this produces good results, but it may not be optimal. For example, a window on two monitors of vastly different color depths could have poor color rendition. Also, monitors with the same color depth may have different color formats—for example, colors could be encoded with different numbers of bits, or be located in different places in a pixel's color value.

To get the best results for each of the monitors in a DC that spans more than one display, call EnumDisplayMonitors to enumerate the monitors that intersect your DC and paint the intersecting area in each of them separately according to the display attributes for that monitor. See the example in Painting on a DC That Spans Multiple Displays.

If you do all of your drawing in your WM_PAINT code and if your WM_PAINT code handles all of the various video modes, then you should be able to place your WM_PAINT code in the MonitorEnumProc of EnumDisplayMonitors with only a few modifications.


Positioning Objects on Multiple Display Monitors

A window or menu that is on more than one monitor causes visual disruption for a viewer. To minimize this problem, the system displays menus and new and maximized windows on one monitor. The following table shows how the monitor is chosen.

Object | Location
window CreateWindow(Ex) displays a window on the monitor that contains the largest part of the window.

Maximizes on the monitor that contains the largest part of the window before it was minimized.

The ALT-TAB key combination displays a window on the monitor that has the currently active window.
owned window | on the same monitor as its owner.
submenu | Appears on the monitor that contains the largest part of the corresponding menu item.
context menu | Appears on the monitor where the right click occurred.
drop-down list | Appears on the monitor that contains the rectangle of the combo box.
dialog box Appears on the monitor of the window that owns it.

If it is defined with DS_CENTERMOUSE style, it appears on the monitor with the mouse.

If it has no owner and the active window and the dialog box are in the same application, the dialog box appears on the monitor of the currently active window.

If the dialog box has no owner and the active window is not in the same application as the dialog box, the dialog box appears on the primary monitor.
message box | Appears on the monitor of the window that owns it.

If a window straddles two monitors and one of the monitors is repositioned, the system positions the window on the monitor that contains the largest part of the original window.

An application will also typically need to position objects. For example, a window may need to be created on the same monitor as another window.

To position an object on a multiple monitor system

  1. Determine the appropriate monitor.
  2. Get the coordinates to the monitor.
  3. Position the object using the coordinates.

Typically, you will position an object either on the primary monitor or on a monitor that has an object already on it. To identify the monitor for a given point, rectangle, or window, use MonitorFromPoint, MonitorFromRect, and MonitorFromWindow.

To get the coordinates for the monitor, use GetMonitorInfo, which provides both the work area and the entire monitor rectangle. Note that SM_CXSCREEN and SM_CYSCREEN always refer to the primary monitor, not necessarily the monitor that displays your application. Also, avoid SM_xxVIRTUALSCREEN because this centers your window on the virtual screen, not a monitor.

To center dialog boxes in a window's work area, use the DS_CENTER style. To center the dialog box to an application window, use GetWindowRect. Windows automatically restricts menus and dialog boxes to a monitor. However, there can be a problem for custom menus, custom drop-down boxes, custom tool palettes, and the saved application position.

For an example of how to position objects correctly, see Positioning Objects on a Multiple Display Setup.

Using SM_CXSCREEN and SM_CYSCREEN to determine the location of an application desktop toolbar (also called appbar) restricts the appbar to the primary monitor. To allow an appbar to be on any edge of any monitor, use the appropriate system metrics to calculate the edges of the monitors. Also, use the GET_X_LPARAM and GET_Y_LPARAM macros to extract the coordinates, otherwise the sign of the coordinates may be wrong. These macros are included in Windowsx.h.

The size of a full-screen window needs to change as it moves among monitors with different resolutions. To do this, the application must check what window it is on, using MonitorFromWindow or MonitorFromPoint, and then use GetMonitorInfo to get the size of the monitor. As an alternative, you could use the HMONITOR from the DirectX DirectDrawEnumerateEx function. Then use SetWindowPos to position and size the window to cover the monitor.

A maximized window does not cover a taskbar that has the "Always on top" property. However, a full-screen window covers the taskbar--for example, in Microsoft® PowerPoint™ slide shows and games.

To save, and later restore, the position of a window when an application exits, use the GetWindowPlacement and SetWindowPlacement functions. However, check that the position is still valid before using it because the monitor could have been moved or removed from the system. The application displays the window on the primary monitor if the HMONITOR of a window is invalid.

The system tries to start an application on the monitor that contains its shortcut. So, one way to position an application is to have its shortcut on a desired monitor.

If you use ShellExecute or ShellExecuteEx, supply an hWnd so the system will open any new windows on the same monitor as the calling application.


MINMAXINFO Changes

The values for the MINMAXINFO structure are slightly altered for a system with multiple monitors. The following table describes the changes.

MINMAXINFO member | Definition for multiple monitors
ptMaxSize | When a window is maximized or resized, this refers to the primary monitor.
ptMaxPosition | Refers to the monitor that the window will maximize on, not the desktop.
ptMinTrackSize | Unchanged.
ptMaxTrackSize | Size for a window that is made as large as the virtual screen.

The system automatically compensates for differences between the primary monitor and the monitor of the window. Thus, if the user leaves ptMaxSize untouched, a window on a monitor larger than the primary monitor will maximize to the size of the larger monitor.


Multiple Monitor Applications on Different Systems

To have your multiple monitor–aware application work both on systems with and without multiple monitor support, link your application with Multimon.h. You must also define COMPILE_MULTIMON_STUBS in exactly one C file. On nonmultiple monitor systems, this returns default values from GetSystemMetrics, and the multiple monitor functions act as if there is only one display. On multiple monitor systems, your application will work normally. If your application is written only for Windows 2000 and Windows 98, you do not need to link with Multimon.h.

Because negative coordinates can happen easily in a multimonitor system, you should retrieve coordinates that are packed in the lParam by using the GET_X_LPARAM and GET_Y_LPARAM macros.

Do not use negative coordinates or coordinates larger than SM_CXSCREEN and SM_CYSCREEN to hide a window. Windows that use these limits to hide may appear on another monitor. Likewise, do not use these limits to keep a window visible because this can cause a window to snap to the primary monitor. It is best to reexamine existing applications for these problems. However, you can minimize problems in existing applications by running the application on the primary monitor or by keeping the primary monitor in the upper-left corner of the virtual screen.

Note that SM_CXMAXTRACK and SM_CYMAXTRACK are defined for the desktop, not just one monitor. Windows using these limits may need to be redefined.

A parent or related window might not be on the same monitor as a child window. To locate the monitor of a window, applications should use the MonitorFromWindow function.

To have a screen saver display on all monitors, link with the latest version of Scrnsave.lib. Otherwise, the screen saver may only appear on the primary monitor and leave the other monitors untouched. Screen savers linked with the latest Scrnsav.lib will work on both single and multiple monitor systems. To have a different screen saver on each monitor, use the multiple monitor functions to handle each monitor separately.

Input devices that deliver coordinates to the system in absolute coordinates, such as tablets, have their cursor input restricted to the primary monitor. To switch tablet input between monitors, see the instructions from the OEM.

Windows 2000: To map mouse input that is sent in absolute coordinates to the entire virtual screen, use the INPUT structure with MOUSEEVENTF_ABSOLUTE and MOUSEEVENTF_VIRTUALDESKTOP.

The BitBlt function works well for multiple monitor systems. However, the MaskBlt, PlgBlt, StretchBlt, and TransparentBlt functions will fail if the source and destination device contexts are different.

The ANTIALIASED_QUALITY setting for CreateFont is not supported on Windows 95/98 in a multiple display monitor setup.


Multiple Monitor Considerations for Older Programs

Generally, older applications do not need changes to work on multiple monitor systems. For most, the system will appear to have only one display. System metrics reflect the primary display and fullscreen applications show up on the primary. The system handles minimization, maximization, menus, and dialog boxes.

However, some programs will have problems. Some that could have problems are remote control applications, those that have direct hardware access, and those that have patched the GDI or DISPLAY driver. In these cases, the user may be required to disable any monitor beyond the primary monitor.


Using Multiple Display Monitors

The examples in this section deal with different aspects of using Multiple Display Monitors.

  • Painting on a DC That Spans Multiple Displays
  • Positioning Objects on a Multiple Display Setup


Painting on a DC That Spans Multiple Displays

To respond to a WM_PAINT message, use code like the following.

case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
EnumDisplayMonitors(hdc, NULL, MyPaintEnumProc, 0);
EndPaint(hwnd, &ps);

To paint the top half of a window, use code like the following.

GetClient Rect(hwnd, &rc);
rc.bottom = (rc.bottom - rc.top) / 2;
hdc = GetDC(hwnd);
EnumDisplayMonitors(hdc, &rc, MyPaintEnumProc, 0);
ReleaseDC(hwnd, hdc);

To paint the entire virtual screen optimally for each monitor, use code like the following.

hdc = GetDC(NULL);
EnumDisplayMonitors(hdc, NULL, MyPaintScreenEnumProc, 0);
ReleaseDC(NULL, hdc);


Positioning Objects on a Multiple Display Setup

The following sample code demonstrates how applications can correctly position objects on multiple displays. Note, do not assume that the RECT is based on the origin (0,0).

#include <windows.h>
#include "multimon.h"

#define MONITOR_CENTER     0x0001        // center rect to monitor
#define MONITOR_CLIP     0x0000        // clip rect to monitor
#define MONITOR_WORKAREA 0x0002        // use monitor work area
#define MONITOR_AREA     0x0000        // use monitor entire area

//
//  ClipOrCenterRectToMonitor
//
//  The most common problem apps have when running on a
//  multimonitor system is that they "clip" or "pin" windows
//  based on the SM_CXSCREEN and SM_CYSCREEN system metrics.
//  Because of app compatibility reasons these system metrics
//  return the size of the primary monitor.
//
//  This shows how you use the new Win32 multimonitor APIs
//  to do the same thing.
//
void ClipOrCenterRectToMonitor(LPRECT prc, UINT flags)
{
    HMONITOR hMonitor;
    MONITORINFO mi;
    RECT        rc;
    int         w = prc->right  - prc->left;
    int         h = prc->bottom - prc->top;

    //
    // get the nearest monitor to the passed rect.
    //
    hMonitor = MonitorFromRect(prc, MONITOR_DEFAULTTONEAREST);

    //
    // get the work area or entire monitor rect.
    //
    mi.cbSize = sizeof(mi);
    GetMonitorInfo(hMonitor, &mi);

    if (flags & MONITOR_WORKAREA)
        rc = mi.rcWork;
    else
        rc = mi.rcMonitor;

    //
    // center or clip the passed rect to the monitor rect
    //
    if (flags & MONITOR_CENTER)
    {
        prc->left   = rc.left + (rc.right  - rc.left - w) / 2;
        prc->top    = rc.top  + (rc.bottom - rc.top  - h) / 2;
        prc->right  = prc->left + w;
        prc->bottom = prc->top  + h;
    }
    else
    {
        prc->left   = max(rc.left, min(rc.right-w,  prc->left));
        prc->top    = max(rc.top,  min(rc.bottom-h, prc->top));
        prc->right  = prc->left + w;
        prc->bottom = prc->top  + h;
    }
}

void ClipOrCenterWindowToMonitor(HWND hwnd, UINT flags)
{
    RECT rc;
    GetWindowRect(hwnd, &rc);
    ClipOrCenterRectToMonitor(&rc, flags);
    SetWindowPos(hwnd, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}


Multiple Display Monitors Reference

The following elements provide support for multiple monitors:

  • Multiple Display Monitors Functions
  • Multiple Display Monitors Structures


Multiple Display Monitors Functions

The following functions provide support for multiple monitors.

Function | Description
EnumDisplayMonitors | Enumerates display monitors that intersect a region formed by the intersection of a specified clipping rectangle and the visible region of a device context.
GetMonitorInfo | Retrieves information about a display monitor.
MonitorEnumProc | An application-defined callback function that is called by the EnumDisplayMonitors function.
MonitorFromPoint | Retrieves a handle to the display monitor that contains a specified point.
MonitorFromRect | Retrieves a handle to the display monitor that has the largest area of intersection with a specified rectangle.
MonitorFromWindow | Retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window.


EnumDisplayMonitors

The EnumDisplayMonitors function enumerates display monitors (including invisible pseudo-monitors associated with the mirroring drivers) that intersect a region formed by the intersection of a specified clipping rectangle and the visible region of a device context. EnumDisplayMonitors calls an application-defined MonitorEnumProc callback function once for each monitor that is enumerated. Note that GetSystemMetrics(SM_CMONITORS) counts only the display monitors.

BOOL EnumDisplayMonitors(
  HDC hdc,                   // handle to display DC
  LPCRECT lprcClip,          // clipping rectangle
  MONITORENUMPROC lpfnEnum,  // callback function
  LPARAM dwData              // data for callback function
);

Parameters

hdc
[in] Handle to a display device context that defines the visible region of interest.

If this parameter is NULL, the hdcMonitor parameter passed to the callback function will be NULL, and the visible region of interest is the virtual screen that encompasses all the displays on the desktop.

lprcClip
[in] Pointer to a RECT structure that specifies a clipping rectangle. The region of interest is the intersection of the clipping rectangle with the visible region specified by hdc.

If hdc is non-NULL, the coordinates of the clipping rectangle are relative to the origin of the hdc. If hdc is NULL, the coordinates are virtual-screen coordinates.

This parameter can be NULL if you don't want to clip the region specified by hdc.

lpfnEnum
[in] Pointer to a MonitorEnumProc application-defined callback function.
dwData
[in] Application-defined data that EnumDisplayMonitors passes directly to the MonitorEnumProc function.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

There are two reasons to call the EnumDisplayMonitors function:

  • You want to draw optimally into a device context that spans several display monitors, and the monitors have different color formats.
  • You want to obtain a handle and position rectangle for one or more display monitors.

To determine whether all the display monitors in a system share the same color format, call GetSystemMetrics(SM_SAMEDISPLAYFORMAT).

You do not need to use the EnumDisplayMonitors function when a window spans display monitors that have different color formats. You can continue to paint under the assumption that the entire screen has the color properties of the primary monitor. Your windows will look fine. EnumDisplayMonitors just lets you make them look better.

Setting the hdc parameter to NULL lets you use the EnumDisplayMonitors function to obtain a handle and position rectangle for one or more display monitors. The following table shows how the four combinations of NULL and non-NULL hdc and lprcClip values affect the behavior of the EnumDisplayMonitors function.

hdc | lprcRect | EnumDisplayMonitors behavior
NULL | NULL | Enumerates all display monitors. The callback function receives a NULL HDC.
NULL | non-NULL | Enumerates all display monitors that intersect the clipping rectangle. Use virtual screen coordinates for the clipping rectangle. The callback function receives a NULL HDC.
non-NULL | NULL | Enumerates all display monitors that intersect the visible region of the device context. The callback function receives a handle to a DC for the specific display monitor.
non-NULL | non-NULL | Enumerates all display monitors that intersect the visible region of the device context and the clipping rectangle. Use device context coordinates for the clipping rectangle. The callback function receives a handle to a DC for the specific display monitor.

Examples

To paint in response to a WM_PAINT message, using the capabilities of each monitor, you can use code like this in a window procedure:

case WM_PAINT:
  hdc = BeginPaint(hwnd, &ps);
  EnumDisplayMonitors(hdc, NULL, MyPaintEnumProc, 0);
  EndPaint(hwnd, &ps);

To paint the top half of a window using the capabilities of each monitor, you can use code like this:

GetClientRect(hwnd, &rc);
rc.bottom = (rc.bottom - rc.top) / 2;
hdc = GetDC(hwnd);
EnumDisplayMonitors(hdc, &rc, MyPaintEnumProc, 0);
ReleaseDC(hwnd, hdc);

To paint the entire virtual screen optimally for each display monitor, you can use code like this:

hdc = GetDC(NULL);
EnumDisplayMonitors(hdc, NULL, MyPaintScreenEnumProc, 0);
ReleaseDC(NULL, hdc);

To get information about all of the display monitors, use code like this:

EnumDisplayMonitors(NULL, NULL, MyInfoEnumProc, 0);

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, MonitorEnumProc, GetSystemMetrics


GetMonitorInfo

The GetMonitorInfo function retrieves information about a display monitor.

BOOL GetMonitorInfo(
  HMONITOR hMonitor,  // handle to display monitor
  LPMONITORINFO lpmi  // display monitor information
);

Parameters

hMonitor
[in] Handle to the display monitor of interest.
lpmi
[out] Pointer to a MONITORINFO or MONITORINFOEX structure that receives information about the specified display monitor.

You must set the cbSize member of the structure to sizeof(MONITORINFO) or sizeof(MONITORINFOEX) before calling the GetMonitorInfo function. Doing so lets the function determine the type of structure you are passing to it.

The MONITORINFOEX structure is a superset of the MONITORINFO structure. It has one additional member: a string that contains a name for the display monitor. Most applications have no use for a display monitor name, and so can save some bytes by using a MONITORINFO structure.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, MONITORINFO, MONITORINFOEX


MonitorEnumProc

A MonitorEnumProc function is an application-defined callback function that is called by the EnumDisplayMonitors function.

A value of type MONITORENUMPROC is a pointer to a MonitorEnumProc function.

BOOL CALLBACK MonitorEnumProc(
  HMONITOR hMonitor,  // handle to display monitor
  HDC hdcMonitor,     // handle to monitor DC
  LPRECT lprcMonitor, // monitor intersection rectangle
  LPARAM dwData       // data
);

Parameters

hMonitor
[in] Handle to the display monitor. This value will always be non-NULL.
hdcMonitor
[in] Handle to a device context.

The device context has color attributes that are appropriate for the display monitor identified by hMonitor. The clipping area of the device context is set to the intersection of the visible region of the device context identified by the hdc parameter of EnumDisplayMonitors, the rectangle pointed to by the lprcClip parameter of EnumDisplayMonitors, and the display monitor rectangle.

This value is NULL if the hdc parameter of EnumDisplayMonitors was NULL.

lprcMonitor
[in] Pointer to a RECT structure.

If hdcMonitor is non-NULL, this rectangle is the intersection of the clipping area of the device context identified by hdcMonitor and the display monitor rectangle. The rectangle coordinates are device-context coordinates.

If hdcMonitor is NULL, this rectangle is the display monitor rectangle. The rectangle coordinates are virtual-screen coordinates.

dwData
[in] Application-defined data that EnumDisplayMonitors passes directly to the enumeration function.

Return Values

To continue the enumeration, return TRUE.

To stop the enumeration, return FALSE.

Remarks

You can use the EnumDisplayMonitors function to enumerate the set of display monitors that intersect the visible region of a specified device context and, optionally, a clipping rectangle. To do this, set the hdc parameter to a non-NULL value, and set the lprcClip parameter as needed.

You can also use the EnumDisplayMonitors function to enumerate one or more of the display monitors on the desktop, without supplying a device context. To do this, set the hdc parameter of EnumDisplayMonitors to NULL and set the lprcClip parameter as needed.

In all cases, EnumDisplayMonitors calls a specified MonitorEnumProc function once for each display monitor in the calculated enumeration set. The MonitorEnumProc function always receives a handle to the display monitor.

If the hdc parameter of EnumDisplayMonitors is non-NULL, the MonitorEnumProc function also receives a handle to a device context whose color format is appropriate for the display monitor. You can then paint into the device context in a manner that is optimal for the display monitor.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, EnumDisplayMonitors


MonitorFromPoint

The MonitorFromPoint function retrieves a handle to the display monitor that contains a specified point.

HMONITOR MonitorFromPoint(
  POINT pt,      // point
  DWORD dwFlags  // determine return value
);

Parameters

pt
[in] A POINT structure that specifies the point of interest in virtual-screen coordinates.
dwFlags
[in] Determines the function's return value if the point is not contained within any display monitor.

This parameter can be one of the following values.
Value | Meaning
MONITOR_DEFAULTTONEAREST | Returns a handle to the display monitor that is nearest to the point.
MONITOR_DEFAULTTONULL | Returns NULL.
MONITOR_DEFAULTTOPRIMARY | Returns a handle to the primary display monitor.

Return Values

If the point is contained by a display monitor, the return value is an HMONITOR handle to that display monitor.

If the point is not contained by a display monitor, the return value depends on the value of dwFlags.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, MonitorFromRect, MonitorFromWindow


MonitorFromRect

The MonitorFromRect function retrieves a handle to the display monitor that has the largest area of intersection with a specified rectangle.

HMONITOR MonitorFromRect(
  LPCRECT lprc,    // rectangle
  DWORD dwFlags    // determine return value
);

Parameters

lprc
[in] Pointer to a RECT structure that specifies the rectangle of interest in virtual-screen coordinates.
dwFlags
[in] Determines the function's return value if the rectangle does not intersect any display monitor.

This parameter can be one of the following values.
Value | Meaning
MONITOR_DEFAULTTONEAREST | Returns a handle to the display monitor that is nearest to the rectangle.
MONITOR_DEFAULTTONULL | Returns NULL.
MONITOR_DEFAULTTOPRIMARY | Returns a handle to the primary display monitor.

Return Values

If the rectangle intersects one or more display monitor rectangles, the return value is an HMONITOR handle to the display monitor that has the largest area of intersection with the rectangle.

If the rectangle does not intersect a display monitor, the return value depends on the value of dwFlags.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, MonitorFromPoint, MonitorFromWindow


MonitorFromWindow

The MonitorFromWindow function retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window.

HMONITOR MonitorFromWindow(
  HWND hwnd,       // handle to a window
  DWORD dwFlags    // determine return value
);

Parameters

hwnd
[in] Handle to the window of interest.
dwFlags
[in] Determines the function's return value if the window does not intersect any display monitor.

This parameter can be one of the following values.
Value | Meaning
MONITOR_DEFAULTTONEAREST | Returns a handle to the display monitor that is nearest to the window.
MONITOR_DEFAULTTONULL | Returns NULL.
MONITOR_DEFAULTTOPRIMARY | Returns a handle to the primary display monitor.

Return Values

If the window intersects one or more display monitor rectangles, the return value is an HMONITOR handle to the display monitor that has the largest area of intersection with the window.

If the window does not intersect a display monitor, the return value depends on the value of dwFlags.

Remarks

If the window is currently minimized, MonitorFromWindow uses the rectangle of the window before it was minimized.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Functions, MonitorFromPoint, MonitorFromRect


Multiple Display Monitors Structures

The following structures are used with the monitor functions.

MONITORINFO
MONITORINFOEX


MONITORINFO

The MONITORINFO structure contains information about a display monitor.

The GetMonitorInfo function stores information in a MONITORINFO structure or a MONITORINFOEX structure.

The MONITORINFO structure is a subset of the MONITORINFOEX structure. The MONITORINFOEX structure adds a string member to contain a name for the display monitor.

typedef struct tagMONITORINFO {
    DWORD  cbSize;
    RECT   rcMonitor;
    RECT   rcWork;
    DWORD  dwFlags;
} MONITORINFO, *LPMONITORINFO;

Members

cbSize
The size of the structure, in bytes.

Set the cbSize member to sizeof(MONITORINFO) before calling the GetMonitorInfo function. Doing so lets the function determine the type of structure you are passing to it.

rcMonitor
A RECT structure that specifies the display monitor rectangle, expressed in virtual-screen coordinates. Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
rcWork
A RECT structure that specifies the work area rectangle of the display monitor, expressed in virtual-screen coordinates. Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
dwFlags
A set of flags that represent attributes of the display monitor.

The following flag is defined.
Value | Meaning
MONITORINFOF_PRIMARY | This is the primary display monitor.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Structures, GetMonitorInfo, MONITORINFOEX


MONITORINFOEX

The MONITORINFOEX structure contains information about a display monitor.

The GetMonitorInfo function stores information into a MONITORINFOEX structure or a MONITORINFO structure.

The MONITORINFOEX structure is a superset of the MONITORINFO structure. The MONITORINFOEX structure adds a string member to contain a name for the display monitor.

typedef struct tagMONITORINFOEX {
    DWORD  cbSize;
    RECT   rcMonitor;
    RECT   rcWork;
    DWORD  dwFlags;
    TCHAR  szDevice[CCHDEVICENAME];
} MONITORINFOEX, *LPMONITORINFOEX;

Members

cbSize
The size, in bytes, of the structure.

Set the cbSize member to sizeof(MONITORINFOEX) before calling the GetMonitorInfo function. Doing so lets the function determine the type of structure you are passing to it.

rcMonitor
A RECT structure that specifies the display monitor rectangle, expressed in virtual-screen coordinates. Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
rcWork
A RECT structure that specifies the work area rectangle of the display monitor, expressed in virtual-screen coordinates. Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
dwFlags
Specifies attributes of the display monitor.

This member can be the following value.
Value | Meaning
MONITORINFOF_PRIMARY | This is the primary display monitor.

szDevice
A string that specifies the name of the display monitor.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Multiple Display Monitors Overview, Multiple Display Monitors Structures, GetMonitorInfo, MONITORINFO


Painting and Drawing

This overview describes how the system manages output to the screen and explains what applications must do to draw in a window. In particular, this overview describes display device contexts (or, more simply, display DCs) and how to prepare and use them. The overview does not explain how to use graphics device interface (GDI) functions to generate output, nor does it explain how to print.

  • About Painting and Drawing
  • Using the WM_PAINT Message
  • Using the GetDC Function
  • Painting and Drawing Reference


About Painting and Drawing

Nearly all applications use the screen to display the data they manipulate. An application paints images, draws figures, and writes text so that the user can view data as it is created, edited, and printed. The Microsoft® Win32® API provides rich support for painting and drawing, but, because of the nature of multitasking operating systems, applications must cooperate with one another when accessing the screen.

To keep all applications functioning smoothly and cooperatively, the system manages all output to the screen. Applications use windows as their primary output device rather than the screen itself. The system supplies display device contexts that uniquely correspond to the windows. Applications use display device contexts to direct their output to the specified windows. Drawing in a window (directing output to it) prevents an application from interfering with the output of other applications and allows applications to coexist with one another while still taking full advantage of the graphics capabilities of the system.

  • When to Draw in a Window
  • The WM_PAINT Message
  • Drawing Without the WM_PAINT Message
  • Window Coordinate System
  • Window Regions
  • Window Background
  • Minimized Windows
  • Resized Windows
  • Nonclient Area
  • Child Window Update Region
  • Display Devices
  • Window Update Lock
  • Accumulated Bounding Rectangle


When to Draw in a Window

An application draws in a window at a variety of times: when first creating a window, when changing the size of the window, when moving the window from behind another window, when minimizing or maximizing the window, when displaying data from an opened file, and when scrolling, changing, or selecting a portion of the displayed data.

The system manages actions such as moving and sizing a window. If an action affects the content of the window, the system marks the affected portion of the window as ready for updating and, at the next opportunity, sends a WM_PAINT message to the window procedure of the window. The message is a signal to the application to determine what must be updated and to carry out the necessary drawing.

Some actions are managed by the application, such as displaying open files and selecting displayed data. For these actions, an application can mark for updating the portion of the window affected by the action, causing a WM_PAINT message to be sent at the next opportunity. If an action requires immediate feedback, the application can draw while the action takes place, without waiting for WM_PAINT. For example, a typical application highlights the area the user selects rather than waiting for the next WM_PAINT message to update the area.

In all cases, an application can draw in a window as soon as it is created. To draw in the window, the application must first retrieve a handle to a display device context for the window. Ideally, an application carries out most of its drawing operations during the processing of WM_PAINT messages. In this case, the application retrieves a display device context by calling the BeginPaint function. If an application draws at any other time, such as from within WinMain or during the processing of keyboard or mouse messages, it calls the GetDC or GetDCEx function to retrieve the display DC.


The WM_PAINT Message

Typically, an application draws in a window in response to a WM_PAINT message. The system sends this message to a window procedure when changes to the window have altered the content of the client area. The system sends the message only if there are no other messages in the application message queue.

Upon receiving a WM_PAINT message, an application can call BeginPaint to retrieve the display device context for the client area and use it in calls to GDI functions to carry out whatever drawing operations are necessary to update the client area. After completing the drawing operations, the application calls the EndPaint function to release the display device context.

Before BeginPaint returns the display device context, the system prepares the device context for the specified window. It first sets the clipping region for the device context to be equal to the intersection of the portion of the window that needs updating and the portion that is visible to the user. Only those portions of the window that have changed are redrawn. Attempts to draw outside this region are clipped and do not appear on the screen.

The system can also send WM_NCPAINT and WM_ERASEBKGND messages to the window procedure before BeginPaint returns. These messages direct the application to draw the nonclient area and window background. The nonclient area is the part of a window that is outside of the client area. The area includes features such as the title bar, window menu (also known as the System menu), and scroll bars. Most applications rely on the default window function, DefWindowProc, to draw this area and therefore pass the WM_NCPAINT message to this function. The window background is the color or pattern that a window is filled with before other drawing operations begin. The background covers any images previously in the window or on the screen under the window. If a window belongs to a window class having a class background brush, the DefWindowProc function draws the window background automatically.

BeginPaint fills a PAINTSTRUCT structure with information such as the dimensions of the portion of the window to be updated and a flag indicating whether the window background has been drawn. The application can use this information to optimize drawing. For example, it can use the dimensions of the update region, specified by the rcPaint member, to limit drawing to only those portions of the window that need updating. If an application has very simple output, it can ignore the update region and draw in the entire window, relying on the system to discard (clip) any unneeded output. Because the system clips drawing that extends outside the clipping region, only drawing that is in the update region is visible.

BeginPaint sets the update region of a window to NULL. This clears the region, preventing it from generating subsequent WM_PAINT messages. If an application processes a WM_PAINT message but does not call BeginPaint or otherwise clear the update region, the application continues to receive WM_PAINT messages as long as the region is not empty. In all cases, an application must clear the update region before returning from the WM_PAINT message.

After the application finishes drawing, it should call EndPaint. For most windows, EndPaint releases the display device context, making it available to other windows. EndPaint also shows the caret, if it was previously hidden by BeginPaint. BeginPaint hides the caret to prevent drawing operations from corrupting it.


The Update Region

The update region identifies the portion of a window that is out-of-date or invalid and in need of redrawing. The system uses the update region to generate WM_PAINT messages for applications and to minimize the time applications spend bringing the contents of their windows up to date. The system adds only the invalid portion of the window to the update region, requiring only that portion to be drawn.

When the system determines that a window needs updating, it sets the dimensions of the update region to the invalid portion of the window. Setting the update region does not immediately cause the application to draw. Instead, the application continues retrieving messages from the application message queue until no messages remain. The system then checks the update region, and if the region is not empty (non-NULL), it sends a WM_PAINT message to the window procedure.

An application can use the update region to generate its WM_PAINT messages. For example, an application that loads data from open files typically sets the update region while loading so that new data is drawn during processing of the next WM_PAINT message. In general, an application should not draw at the time its data changes, but route all drawing operations through the WM_PAINT message.


Invalidating and Validating the Update Region

An application invalidates a portion of a window and sets the update region by using the InvalidateRect or InvalidateRgn function. These functions add the specified rectangle or region (in client coordinates) to the update region, combining the rectangle or region with anything the system or the application may have previously added to the update region.

The InvalidateRect and InvalidateRgn functions do not generate WM_PAINT messages. Instead, the system accumulates the changes made by these functions and its own changes while a window processes other messages in its message queue. By accumulating changes, a window processes all changes at once instead of updating bits and pieces one step at a time.

The ValidateRect and ValidateRgn functions validate a portion of the window by removing a specified rectangle or region from the update region. These functions are typically used when the window has updated a specific part of the screen in the update region before receiving the WM_PAINT message.


Retrieving the Update Region

The GetUpdateRect and GetUpdateRgn functions retrieve the current update region for the window. GetUpdateRect retrieves the smallest rectangle (in logical coordinates) that encloses the entire update region. GetUpdateRgn retrieves the update region itself. These functions can be used to calculate the current size of the update region to determine where to carry out a drawing operation.

BeginPaint also retrieves the dimensions of the smallest rectangle enclosing the current update region, copying the dimensions to the rcPaint member in the PAINTSTRUCT structure. Because BeginPaint validates the update region, any call to GetUpdateRect and GetUpdateRgn immediately after a call to BeginPaint returns an empty update region.


Excluding the Update Region

The ExcludeUpdateRgn function excludes the update region from the clipping region for the display device context. This function is useful when drawing in a window other than when a WM_PAINT message is processing. It prevents drawing in the areas that will be updated during the next WM_PAINT message.


Synchronous and Asynchronous Drawing

Most drawing carried out during processing of the WM_PAINT message is asynchronous; that is, there is a delay between the time a portion of the window is invalidated and the time WM_PAINT is sent. During the delay, the application typically retrieves messages from the queue and carries out other tasks. The reason for the delay is that the system generally treats drawing in a window as a low-priority operation and works as though user-input messages and messages that may affect the position or size of a window will be processed before WM_PAINT.

In some cases, it is necessary for an application to draw synchronously — that is, draw in the window immediately after invalidating a portion of the window. A typical application draws its main window immediately after creating the window to signal the user that the application has started successfully. The system draws some control windows synchronously, such as buttons, because such windows serve as the focus for user input. Although any window with a simple drawing routine can be drawn synchronously, all such drawing should be done quickly and should not interfere with the application's ability to respond to user input.

The UpdateWindow and RedrawWindow functions allow for synchronous drawing. UpdateWindow sends a WM_PAINT message directly to the window if the update region is not empty. RedrawWindow also sends a WM_PAINT message, but gives the application greater control over how to draw the window, such as whether to draw the nonclient area and window background or whether to send the message regardless of whether the update region is empty. These functions send the WM_PAINT message directly to the window, regardless of the number of other messages in the application message queue.

Any window requiring time-consuming drawing operations should be drawn asynchronously to prevent pending messages from being blocked as the window is drawn. Also, any application that frequently invalidates small portions of a window should allow these invalid portions to consolidate into a single asynchronous WM_PAINT message, rather than a series of synchronous WM_PAINT messages.


Drawing Without the WM_PAINT Message

Although applications carry out most drawing operations while the WM_PAINT message is processing, it is sometimes more efficient for an application to draw directly in a window without relying on the WM_PAINT message. This can be useful when the user needs immediate feedback, such as when selecting text and dragging or sizing an object. In such cases, the application usually draws while processing keyboard or mouse messages.

To draw in a window without using a WM_PAINT message, the application uses the GetDC or GetDCEx function to retrieve a display device context for the window. With the display device context, the application can draw in the window and avoid intruding into other windows. When the application has finished drawing, it calls the ReleaseDC function to release the display device context for use by other applications.

When drawing without using a WM_PAINT message, the application usually does not invalidate the window. Instead, it draws in such a fashion that it can easily restore the window and remove the drawing. For example, when the user selects text or an object, the application typically draws the selection by inverting whatever is already in the window. The application can remove the selection and restore the original contents of the window by simply inverting again.

The application is responsible for carefully managing any changes it makes to the window. In particular, if an application draws a selection and an intervening WM_PAINT message occurs, the application must ensure that any drawing done during the message does not corrupt the selection. To avoid this, many applications remove the selection, carry out usual drawing operations, and then restore the selection when drawing is complete.


Window Coordinate System

The coordinate system for a window is based on the coordinate system of the display device. The basic unit of measure is the device unit (typically, the pixel). Points on the screen are described by x- and y-coordinate pairs. The x-coordinates increase to the right; y-coordinates increase from top to bottom. The origin (0,0) for the system depends on the type of coordinates being used.

The system and applications specify the position of a window on the screen in screen coordinates. For screen coordinates, the origin is the upper-left corner of the screen. The full position of a window is often described by a RECT structure containing the screen coordinates of two points that define the upper-left and lower-right corners of the window.

The system and applications specify the position of points in a window by using client coordinates. The origin in this case is the upper-left corner of the window or client area. Client coordinates ensure that an application can use consistent coordinate values while drawing in the window, regardless of the position of the window on the screen.

The dimensions of the client area are also described by a RECT structure that contains client coordinates for the area. In all cases, the upper-left coordinate of the rectangle is included in the window or client area, while the lower-right coordinate is excluded. Graphics operations in a window or client area are excluded from the right and lower edges of the enclosing rectangle.

Occasionally, applications may be required to map coordinates in one window to those of another window. An application can map coordinates by using the MapWindowPoints function. If one of the windows is the desktop window, the function effectively converts screen coordinates to client coordinates and vice versa; the desktop window is always specified in screen coordinates.


Window Regions

In addition to the update region, every window has a visible region that defines the window portion visible to the user. The system changes the visible region for the window whenever the window changes size or whenever another window is moved such that it obscures or exposes a portion of the window. Applications cannot change the visible region directly, but the system automatically uses the visible region to create the clipping region for any display device context retrieved for the window.

The clipping region determines where the system permits drawing. When the application retrieves a display device context using the BeginPaint, GetDC, or GetDCEx function, the system sets the clipping region for the device context to the intersection of the visible region and the update region. Applications can change the clipping region by using functions such as SetWindowRgn, SelectClipPath and SelectClipRgn, to further limit drawing to a particular portion of the update area.

The WS_CLIPCHILDREN and WS_CLIPSIBLINGS styles further specify how the system calculates the visible region for a window. If a window has one or both of these styles, the visible region excludes any child window or sibling windows (windows having the same parent window). Therefore, drawing that would otherwise intrude in these windows will always be clipped.


Window Background

The window background is the color or pattern used to fill the client area before a window begins drawing. The window background covers whatever was on the screen before the window was moved there, erasing existing images and preventing the application's new output from being mixed with unrelated information.

The system paints the background for a window or gives the window the opportunity to do so by sending it a WM_ERASEBKGND message when the application calls BeginPaint. If an application does not process the message but passes it to DefWindowProc, the system erases the background by filling it with the pattern in the background brush specified by the window's class. If the brush is not valid or the class has no background brush, the system sets the fErase member in the PAINTSTRUCT structure that BeginPaint returns, but carries out no other action. The application then has a second chance to draw the window background, if necessary.

If it processes WM_ERASEBKGND, the application should use the message's wParam parameter to draw the background. This parameter contains a handle to the display device context for the window. After drawing the background, the application should return a nonzero value. This ensures that BeginPaint does not erroneously set the fErase member of the PAINTSTRUCT structure to a nonzero value (indicating the background should be erased) when the application processes the subsequent WM_PAINT message.

An application can define a class background brush by assigning a brush handle or a system color value to the hbrBackground member of the WNDCLASS structure when registering the class with the RegisterClass function. The GetStockObject or CreateSolidBrush function can be used to create a brush handle. A system color value can be one of those defined for the SetSysColors function. (The value must be increased by one before it is assigned to the member.)

An application can process the WM_ERASEBKGND message even though a class background brush is defined. This is typical in applications that enable the user to change the window background color or pattern for a specified window without affecting other windows in the class. In such cases, the application must not pass the message to DefWindowProc.

It is not necessary for an application to align brushes, because the system draws the brush using the window origin as the point of reference. Given this, the user can move the window without affecting the alignment of pattern brushes.


Minimized Windows

The system reduces an application's main window (overlapping style) to a minimized window when the user clicks Minimize from the window menu or the application calls the ShowWindow function and specifies a value such as SW_MINIMIZE. Minimizing a window speeds up system performance by reducing the amount of work an application must do when updating its main window.

For a typical application, the system draws an icon, called the class icon, when the window is minimized, labeling the icon with the name of the window. The class icon, a static image that represents the application, is specified by the application when it registers the window class. The application assigns a handle to the class icon to the hIcon member of WNDCLASS before calling RegisterClass. The application can use the LoadIcon function to retrieve the icon handle.

Before drawing the class icon, the system sends a WM_ICONERASEBKGND message to the window procedure, enabling the application to prepare the background for drawing the icon by setting the best possible background colors for the icon. This is useful for applications that combine the icon with the current background colors. If the application processes the message, it should use the display device context provided with the message to draw the background (the wParam parameter contains a handle to the display DC). If the application does not process the WM_ICONERASEBKGND message, it should pass the message to DefWindowProc; the function fills the icon area with the current desktop color and pattern. After sending the WM_ICONERASEBKGND message, the system sends the WM_PAINTICON message to the window procedure. The application should immediately forward this internal message to DefWindowProc.

The system does not require that a window class have a class icon. If an application sets the hIcon member of WNDCLASS to NULL, a class icon is not defined. In this case, the system sends the WM_ERASEBKGND message (instead of WM_ICONERASEBKGND) to a window of the class whenever the window must paint the icon background. The system then sends a WM_PAINT message and the application draws an icon or another image representing the minimized window. In such cases, the application must determine when the window is minimized and draw accordingly. It can do so by calling the IsIconic function. If the function returns TRUE, the window is minimized. If an application has no class icon and fails to process WM_ERASEBKGND and WM_PAINT, the area that the system reserves for the application's icon will contain whatever was previously on the screen.


Resized Windows

The system changes the size of a window when the user chooses window menu commands, such as Size and Maximize, or when the application calls functions, such as the SetWindowPos function. When a window changes size, the system assumes that the contents of the previously exposed portion of the window are not affected and need not be redrawn. The system invalidates only the newly exposed portion of the window, which saves time when the eventual WM_PAINT message is processed by the application. In this case, WM_PAINT is not generated when the size of the window is reduced.

For some windows, any change to the size of the window invalidates the contents. For example, a clock application that adapts the face of the clock to fit neatly within its window must redraw the clock whenever the window changes size. To force the system to invalidate the entire client area of the window when a vertical, horizontal, or both vertical and horizontal change is made, an application must specify the CS_VREDRAW or CS_HREDRAW style, or both, when registering the window class. Any window belonging to a window class having these styles is invalidated each time the user or the application changes the size of the window.


Nonclient Area

The system sends a WM_NCPAINT message to the window whenever a part of the nonclient area of the window, such as the title bar, menu bar, or window frame, must be updated. The system may also send other messages to direct a window to update a portion of its client area; for example, when a window becomes active or inactive, it sends the WM_NCACTIVATE message to update its title bar. In general, processing these messages for standard windows is not recommended, because the application must be able to draw all the required parts of the nonclient area for the window. For this reason, most applications pass these messages to DefWindowProc for default processing.

An application that creates custom nonclient areas for its windows must process these messages. When doing so, the application must use a window device context to carry out drawing in the window. The window device context enables the application to draw in all portions of the window, including the nonclient area. An application retrieves a window device context by using the GetWindowDC or GetDCEx function and, when drawing is complete, must release the window device context by using the ReleaseDC function.

The system maintains an update region for the nonclient area. When an application receives a WM_NCPAINT message, the wParam parameter contains a handle to a region defining the dimensions of the update region. The application can use the handle to combine the update region with the clipping region for the window device context. The system does not automatically combine the update region when retrieving the window device context unless the application uses GetDCEx and specifies both the region handle and the DCX_INTERSECTRGN flag. If the application does not combine the update region, only drawing operations that would otherwise extend outside the window are clipped. The application is not responsible for clearing the update region, regardless of whether it uses the region.

If an application processes the WM_NCACTIVATE message, after processing it must return TRUE to direct the system to complete the change of active window. If the window is minimized when the application receives the WM_NCACTIVATE message, it should pass the message to DefWindowProc. In such cases, the default function redraws the label for the icon.


Child Window Update Region

A child window is a window with the WS_CHILD or WS_CHILDWINDOW style. Like other window styles, child windows receive WM_PAINT messages to prompt updating. Each child window has an update region, which either the system or the application can set to generate eventual WM_PAINT messages.

A child window's update and visible regions are affected by the child's parent window; this is not true for windows of other styles. The system often sets the child window's update region when it sets the parent window's update region, causing the child window to receive WM_PAINT messages when the parent window receives them. The system limits the location of the child window's visible region to within the client area of the parent window and clips any portion of the child window moved outside the parent window.

The system sets the update region for a child window whenever part of the parent window's update region includes a portion of the child window. In such cases, the system first sends a WM_PAINT message to the parent window and then sends a message to the child window, allowing the child to restore any portions of the window that the parent may have drawn over.

The system does not set the parent's update region when the child's is set. An application cannot generate a WM_PAINT message for the parent window by invalidating the child window. Similarly, an application cannot generate a WM_PAINT message for the child by invalidating a portion of the parent's client area that lies entirely under the child window. In such cases, neither window receives a WM_PAINT message.

An application can prevent a child window's update region from being set when the parent window's is set by specifying the WS_CLIPCHILDREN style when creating the parent window. When this style is set, the system excludes the child windows from the parent's visible region and therefore ignores any portion of the update region that may contain the child windows. When the application paints in the parent window, any drawing that would cover the child window is clipped, making a subsequent WM_PAINT message to the child window unnecessary.

The update and visible regions of a child window are also affected by the child window's siblings. Sibling windows are any windows that have a common parent window. If sibling windows overlap, then setting the update region for one affects the update region of another, causing WM_PAINT messages to be sent to both windows. Sibling windows receive WM_PAINT messages in the reverse order of their position in the Z order. Given this, the window highest in the Z order (on the top) receives its WM_PAINT message last, and vice versa.

Sibling windows are not automatically clipped. One sibling can draw over another overlapping sibling even if the window that is drawing has a lower position in the Z order. An application can prevent this by specifying the WS_CLIPSIBLINGS style when creating the windows. When this style is set, the system excludes all portions of an overlapping sibling window from a window's visible region if the overlapping sibling window has a higher position in the Z order.

Note The update and visible regions for windows that have the WS_POPUP or WS_POPUPWINDOW style are not affected by their parent windows.


Display Devices

Before painting, the system must prepare the display device for drawing operations. A display device context defines a set of graphic objects and their associated attributes, and the graphic modes that affect output. The system prepares each display device context for output to a window, setting the drawing objects, colors, and modes for the window instead of the display device. When the application supplies the display device context through calls to GDI functions, GDI uses the information in the context to generate output in the specified window without intruding on other windows or other parts of the screen.

The system provides five kinds of display device contexts.

Type | Meaning
common | Permits drawing in the client area of a specified window.
class | Permits drawing in the client area of a specified window.
parent | Permits drawing anywhere in the window. Although the parent device context also permits drawing in the parent window, it is not intended to be used in this way.
private | Permits drawing in the client area of a specified window.
window | Permits drawing anywhere in the window.

The system supplies a common, class, parent, or private device context to a window based on the type of display device context specified in that window's class style. The system supplies a window device context only when the application explicitly requests one — for example, by calling the GetWindowDC or GetDCEx function. In all cases, an application can use the WindowFromDC function to determine which window a display DC currently represents.


Display Device Context Cache

The system maintains a cache of display device contexts that it uses for common, parent, and window device contexts. The system retrieves a device context from the cache whenever an application calls the GetDC or BeginPaint function; the system returns the DC to the cache when the application subsequently calls the ReleaseDC or EndPaint function.

In 16-bit Microsoft® Windows®, the cache contains five display device contexts, but only five device contexts from the cache can be active at a time. To ensure that other applications have access to these device contexts, an application must release a device context immediately after using it. Failure to do so eventually causes the application to fail.

There is no predetermined limit on the amount of device contexts that a cache can hold; the system creates a new display device context for the cache if none is available. Given this, a Win32-based application can have more than five active device contexts from the cache at a time. However, the application must continue to release these device contexts after use. Because new display device contexts for the cache are allocated in the application's heap space, failing to release the device contexts eventually consumes all available heap space. The system indicates this failure by returning an error when it cannot allocate space for the new device context. Other functions unrelated to the cache may also return errors.


Display Device Context Defaults

Upon first creating a display device context, the system assigns default values for the attributes (that is, drawing objects, colors, and modes) that comprise the device context. The following table shows the default values for the attributes of a display device context.

Attribute | Default value
Background color | Background color setting from Control Panel (typically, white).
Background mode | OPAQUE
Bitmap | None
Brush | WHITE_BRUSH
Brush origin | (0,0)
Clipping region | Entire window or client area with the update region clipped, as appropriate. Child and pop-up windows in the client area may also be clipped.
Palette | DEFAULT_PALETTE
Current pen position | (0,0)
Device origin | Upper left corner of the window or the client area.
Drawing mode | R2_COPYPEN
Font | SYSTEM_FONT
Intercharacter spacing | 0
Mapping mode | MM_TEXT
Pen | BLACK_PEN
Polygon-fill mode | ALTERNATE
Stretch mode | BLACKONWHITE
Text color | Text color setting from Control Panel (typically, black).
Viewport extent | (1,1)
Viewport origin | (0,0)
Window extent | (1,1)
Window origin | (0,0)

An application can modify the values of the display device context attributes by using selection and attribute functions, such as SelectObject, SetMapMode, and SetTextColor. For example, an application can modify the default units of measure in the coordinate system by using SetMapMode to change the mapping mode.

Changes to the attribute values of a common, parent, or window device context are not permanent. When an application releases these device contexts, the current selections, such as mapping mode and clipping region, are lost as the context is returned to the cache. Changes to a class or private device context persist indefinitely. To restore them to their original defaults, an application must explicitly set each attribute.


Common Display Device Contexts

A common device context is used for drawing in the client area of the window. The system provides a common device context by default for any window whose window class does not explicitly specify a display device context style. Common device contexts are typically used with windows that can be drawn without extensive changes to the device context attributes. Common device contexts are convenient because they do not require additional memory or system resources, but they can be inconvenient if the application must set up many attributes before using them.

The system retrieves all common device contexts from the display device context cache. An application can retrieve a common device context immediately after the window is created. Because the common device context is from the cache, the application must always release the device context as soon as possible after drawing. After the common device context is released, it is no longer valid and the application must not attempt to draw with it. To draw again, the application must retrieve a new common device context, and continue to retrieve and release a common device context each time it draws in the window. If the application retrieves the device context handle by using the GetDC function, it must use the ReleaseDC function to release the handle. Similarly, for each BeginPaint function, the application must use a corresponding EndPaint function.

When the application retrieves the device context, the system adjusts the origin so that it aligns with the upper left corner of the client area. It also sets the clipping region so that output to the device context is clipped to the client area. Any output that would otherwise appear outside the client area is clipped. If the application retrieves the common device context by using BeginPaint, the system also includes the update region in the clipping region to further restrict the output.

When an application releases a common device context, the system restores the default values for the attributes of the device context. An application that modifies attribute values must do so each time it retrieves a common device context. Releasing the device context releases any drawing objects the application may have selected into it, so the application need not release these objects before releasing the device context. In all cases, an application must never assume that the common device context retains nondefault selections after being released.


Private Display Device Contexts

A private device context enables an application to avoid retrieving and initializing a display device context each time the application must draw in a window. Private device contexts are useful for windows that require many changes to the values of the attributes of the device context to prepare it for drawing. Private device contexts reduce the time required to prepare the device context and therefore the time needed to carry out drawing in the window.

An application directs the system to create a private device context for a window by specifying the CS_OWNDC style in the window class. The system creates a unique private device context each time it creates a new window belonging to the class. Initially, the private device context has the same default values for attributes as a common device context, but the application can modify these at any time. The system preserves changes to the device context for the life of the window or until the application makes additional changes.

An application can retrieve a handle to the private device context by using the GetDC function any time after the window is created. The application must retrieve the handle only once. Thereafter, it can keep and use the handle any number of times. Because a private device context is not part of the display device context cache, an application need never release the device context by using the ReleaseDC function.

The system automatically adjusts the device context to reflect changes to the window, such as moving or sizing. This ensures that any overlapping windows are always properly clipped; that is, no action is required by the application to ensure clipping. However, the system does not revise the device context to include the update region. Therefore, when processing a WM_PAINT message, the application must incorporate the update region either by calling BeginPaint or by retrieving the update region and intersecting it with the current clipping region. If the application does not call BeginPaint, it must explicitly validate the update region by using the ValidateRect or ValidateRgn function. If the application does not validate the update region, the window receives an endless series of WM_PAINT messages.

Because BeginPaint hides the caret if a window is showing it, an application that calls BeginPaint should also call the EndPaint function to restore the caret. EndPaint has no other effect on a private device context.

Although a private device context is convenient to use, it is expensive in terms of system resources, requiring 800 or more bytes to store. Private device contexts are recommended when performance considerations outweigh storage costs.

The system includes the private device context when sending the WM_ERASEBKGND message to the application. The current selections of the private device context, including mapping mode, are in effect when the application or the system processes these messages. To avoid undesirable effects, the system uses logical coordinates when erasing the background; for example, it uses the GetClipBox function to retrieve the logical coordinates of the area to erase and passes these coordinates to the FillRect function. Applications that process these messages can use similar techniques. The system supplies a window device context with the WM_ICONERASEBKGND message regardless of whether the corresponding window has a private device context.

An application can use the GetDCEx function to force the system to return a common device context for the window that has a private device context. This is useful for carrying out quick touch-ups to a window without changing the current values of the attributes of the private device context.


Class Display Device Contexts

By using a class device context, an application can use a single display device context for every window belonging to a specified class. Class device contexts are often used with control windows that are drawn using the same attribute values. Like private device contexts, class device contexts minimize the time required to prepare a device context for drawing.

The system supplies a class device context for a window if it belongs to a window class having the CS_CLASSDC style. The system creates the device context when creating the first window belonging to the class and then uses the same device context for all subsequently created windows in the class. Initially, the class device context has the same default values for attributes as a common device context, but the application can modify these at any time. The system preserves all changes, except for the clipping region and device origin, until the last window in the class has been destroyed. A change made for one window applies to all windows in that class.

An application can retrieve the handle for the class device context by using the GetDC function any time after the first window has been created. The application can keep and use the handle without releasing it because the class device context is not part of the display device context cache. If the application creates another window in the same window class, the application must retrieve the class device context again. Retrieving the device context sets the correct device origin and clipping region for the new window. After the application retrieves the class device context for a new window in the class, the device context can no longer be used to draw in the original window without again retrieving it for that window. In general, each time it must draw in a window, an application must explicitly retrieve the class device context for the window.

Applications that use class device contexts should always call BeginPaint when processing a WM_PAINT message. The function sets the correct device origin and clipping region for the window, and incorporates the update region. The application should also call EndPaint to restore the caret if BeginPaint hid it. EndPaint has no other effect on a class device context.

The system passes the class device context when sending the WM_ERASEBKGND message to the application, permitting the current attribute values to affect any drawing carried out by the application or the system when processing this message. The system supplies a window device context with the WM_ICONERASEBKGND message regardless of whether the corresponding window has a class device context. As it could with a window having a private device context, an application can use GetDCEx to force the system to return a common device context for the window that has a class device context.

Using class device contexts is not recommended.


Window Display Device Contexts

A window device context enables an application to draw anywhere in a window, including the nonclient area. Window device contexts are typically used by applications that process the WM_NCPAINT and WM_NCACTIVATE messages for windows with custom nonclient areas. Using a window device context is not recommended for any other purpose.

An application can retrieve a window device context by using the GetWindowDC or GetDCEx function with the DCX_WINDOW option specified. The function retrieves a window device context from the display device context cache. A window that uses a window device context must release it after drawing by using the ReleaseDC function as soon as possible. Window device contexts are always from the cache; the CS_OWNDC and CS_CLASSDC class styles do not affect the device context.

When an application retrieves a window device context, the system sets the device origin to the upper left corner of the window instead of the upper left corner of the client area. It also sets the clipping region to include the entire window, not just the client area. The system sets the current attribute values of a window device context to the same default values as a common device context. An application can change the attribute values, but the system does not preserve any changes when the device context is released.


Parent Display Device Contexts

A parent device context enables an application to minimize the time necessary to set up the clipping region for a window. An application typically uses parent device contexts to speed up drawing for control windows without requiring a private or class device context. For example, the system uses parent device contexts for push button and edit controls. Parent device contexts are intended for use with child windows only, never with top-level or pop-up windows.

An application can specify the CS_PARENTDC style to set the clipping region of the child window to that of the parent window so that the child can draw in the parent. Specifying CS_PARENTDC enhances an application's performance because the system doesn't need to keep recalculating the visible region for each child window.

Attribute values set by the parent window are not preserved for the child window; for example, the parent window cannot set the brush for its child windows. The only property preserved is the clipping region. The window must clip its own output to the limits of the window. Because the clipping region for the parent device context is identical to the parent window, the child window can potentially draw over the entire parent window, but the parent device context must not be used in this way.

the system ignores the CS_PARENTDC style if the parent window uses a private or class device context, if the parent window clips its child windows, or if the child window clips its child windows or sibling windows.


Window Update Lock

A window update lock is a temporary suspension of drawing in a window. The system uses the lock to prevent other windows from drawing over the tracking rectangle whenever the user moves or sizes a window. Applications can use the lock to prevent drawing if they carry out similar moving or sizing operations with their own windows.

An application uses the LockWindowUpdate function to set or clear a window update lock, specifying the window to lock. The lock applies to the specified window and all of its child windows. When the lock is set, the GetDC and BeginPaint functions return a display device context with a visible region that is empty. Given this, the application can continue to draw in the window, but all output is clipped. The lock persists until the application clears it by calling LockWindowUpdate, specifying NULL for the window. Although LockWindowUpdate forces a window's visible region to be empty, the function does not make the specified window invisible and does not clear the WS_VISIBLE style bit.

After the lock is set, the application can use the GetDCEx function, with the DCX_LOCKWINDOWUPDATE value, to retrieve a display device context to draw over the locked window. This allows the application to draw a tracking rectangle when processing keyboard or mouse messages. The system uses this method when the user moves and sizes windows. GetDCEx retrieves the display device context from the display device context cache, so the application must release the device context as soon as possible after drawing.

While a window update lock is set, the system creates an accumulated bounding rectangle for each locked window. When the lock is cleared, the system uses this bounding rectangle to set the update region for the window and its child windows, forcing an eventual WM_PAINT message. If the accumulated bounding rectangle is empty (that is, if no drawing has occurred while the lock was set), the update region is not set.


Accumulated Bounding Rectangle

The accumulated bounding rectangle is the smallest rectangle enclosing the portion of a window or client area affected by recent drawing operations. An application can use this rectangle to conveniently determine the extent of changes caused by drawing operations. It is sometimes used in conjunction with LockWindowUpdate to determine which portion of the client area must be redrawn after the update lock is cleared.

An application uses the SetBoundsRect function (specifying DCB_ENABLE) to begin accumulating the bounding rectangle. The system subsequently accumulates points for the bounding rectangle as the application uses the specified display device context. The application can retrieve the current bounding rectangle at any time by using the GetBoundsRect function. The application stops the accumulation by calling SetBoundsRect again, specifying the DCB_DISABLE value.


Using the WM_PAINT Message

You can use the WM_PAINT message to carry out the drawing necessary for displaying information. Because the system sends WM_PAINT messages to your application when your window must be updated or when you explicitly request an update, you can consolidate the code for drawing in your application's window procedure. You can then use this code whenever your application must draw either new or existing information.

The following sections show a variety of ways to use the WM_PAINT message to draw in a window:

  • Drawing in the Client Area
  • Redrawing the Entire Client Area
  • Redrawing in the Update Region
  • Invalidating the Client Area
  • Drawing a Minimized Window
  • Drawing a Custom Window Background


Drawing in the Client Area

You use the BeginPaint and EndPaint functions to prepare for and complete the drawing in the client area. BeginPaint returns a handle to the display device context used for drawing in the client area; EndPaint ends the paint request and releases the device context.

In the following example, the window procedure writes the message "Hello, Windows!" in the client area. To make sure the string is visible when the window is first created, the WinMain function calls UpdateWindow immediately after creating and showing the window. This causes a WM_PAINT message to be sent immediately to the window procedure.

LRESULT APIENTRY WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            TextOut(hdc, 0, 0, "Hello, Windows!", 15);
            EndPaint(hwnd, &ps);
            return 0L;

        // Process other messages.
    }
}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hwnd;

    hwnd = CreateWindowEx(
        // parameters
        );

    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);

    return msg.wParam;
}


Redrawing the Entire Client Area

You can have your application redraw the entire contents of the client area whenever the window changes size by setting the CS_HREDRAW and CS_VREDRAW styles for the window class. Applications that adjust the size of the drawing based on the size of the window use these styles to ensure that they start with a completely empty client area when drawing.

In the following example, the window procedure draws a five-pointed star that fits neatly in the client area. It uses a common device context and must set the mapping mode as well as window and viewport extents each time the WM_PAINT message is processed.

LRESULT APIENTRY WndProc(HWMD hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    RECT rc;
    POINT aptStar[6] = {50,2, 2,98, 98,33, 2,33, 98,98, 50,2};

    .
    .
    .

        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            GetClientRect(hwnd, &rc);
            SetMapMode(hdc, MM_ANISOTROPIC);
            SetWindowExtEx(hdc, 100, 100, NULL);
            SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);
            Polyline(hdc, aptStar, 6);
            EndPaint(hwnd, &ps);
            return 0L;

        .
        .
        .
}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASS wc;

    .
    .
    .

        wc.style = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc = (WNDPROC) WndProc;

    .
    .
    .

        RegisterClass(&wc);

    .
    .
    .

    return msg.wParam;
}


Redrawing in the Update Region

You can limit the amount of drawing your application carries out when processing the WM_PAINT message by determining the size and location of the update region. Because the system uses the update region when creating the clipping region for the window's display device context, you can indirectly determine the update region by examining the clipping region.

In the following example, the window procedure draws a triangle, a rectangle, a pentagon, and a hexagon, but only if all or a portion of each figure lies within the update region. The window procedure uses the RectVisible function and a 100-by-100 rectangle to determine whether a figure is within the clipping region (and therefore the update region) for the common device context retrieved by BeginPaint.

POINT aptTriangle[4]  = {50,2, 98,86,  2,86, 50,2},
      aptRectangle[5] = { 2,2, 98,2,  98,98,  2,98, 2,2},
      aptPentagon[6]  = {50,2, 98,35, 79,90, 21,90, 2,35, 50,2},
      aptHexagon[7]   = {50,2, 93,25, 93,75, 50,98, 7,75, 7,25, 50,2};
  .
  .
  .

        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            SetRect(&rc, 0, 0, 100, 100);

            if (RectVisible(hdc, &rc))
                Polyline(hdc, aptTriangle, 4);

            SetViewportOrgEx(hdc, 100, 0, NULL);
            if (RectVisible(hdc, &rc))
                Polyline(hdc, aptRectangle, 5);

            SetViewportOrgEx(hdc, 0, 100, NULL);
            if (RectVisible(hdc, &rc))
                Polyline(hdc, aptPentagon, 6);

            SetViewportOrgEx(hdc, 100, 100, NULL);
            if (RectVisible(hdc, &rc))
                Polyline(hdc, aptHexagon, 7);
            EndPaint(hwnd, &ps);
            return 0L;

  .
  .
  .

The coordinates of each figure in this example lie within the same 100-by-100 rectangle. Before drawing a figure, the window procedure sets the viewport origin to a different part of the client area by using the SetViewportOrgEx function. This prevents figures from being drawn one on top of the other. Changing the viewport origin does not affect the clipping region, but does affect how the coordinates of the rectangle passed to RectVisible are interpreted. Changing the origin also allows you to use a single rectangle to check the update region rather than individual rectangles for each figure.


Invalidating the Client Area

The system is not the only source of WM_PAINT messages. The InvalidateRect or InvalidateRgn function can indirectly generate WM_PAINT messages for your windows. These functions mark all or part of a client area as invalid (that must be redrawn).

In the following example, the window procedure invalidates the entire client area when processing WM_CHAR messages. This allows the user to change the figure by typing a number and view the results; these results are drawn as soon as there are no other messages in the application's message queue.

POINT aptPentagon[6] = {50,2, 98,35, 79,90, 21,90, 2,35, 50,2},
      aptHexagon[7]  = {50,2, 93,25, 93,75, 50,98, 7,75, 7,25, 50,2};
POINT *ppt = aptPentagon;
int cpt = 6;

  .
  .
  .

case WM_CHAR:
    switch (wParam)
    {
        case '5':
            ppt = aptPentagon;
            cpt = 6;
            break;
        case '6':
            ppt = aptHexagon;
            cpt = 7;
            break;
    }
    InvalidateRect(hwnd, NULL, TRUE);
    return 0L;

case WM_PAINT:
    hdc = BeginPaint(hwnd, &ps);
    GetClientRect(hwnd, &rc);
    SetMapMode(hdc, MM_ANISOTROPIC);
    SetWindowExtEx(hdc, 100, 100, NULL);
    SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);
    Polyline(hdc, ppt, cpt);
    EndPaint(hwnd, &ps);
    return 0L;

In this example, the NULL argument used by InvalidateRect specifies the entire client area; the TRUE argument causes the background to be erased. If you do not want the application to wait until the application's message queue has no other messages, use the UpdateWindow function to force the WM_PAINT message to be sent immediately. If there is any invalid part of the client area, UpdateWindow sends the WM_PAINT message for the specified window directly to the window procedure.


Drawing a Minimized Window

You can draw your own minimized windows rather than having the system draw them for you. Most applications define a class icon when registering the window class for the window, and the system draws the icon when the window is minimized. If you set the class icon to NULL, however, the system sends a WM_PAINT message to your window procedure whenever the window is minimized, enabling the window procedure to draw in the minimized window.

In the following example, the window procedure draws a star in the minimized window. The procedure uses the IsIconic function to determine when the window is minimized. This ensures that the star is drawn only when the window is minimized.

POINT aptStar[6] = {50,2, 2,98, 98,33, 2,33, 98,98, 50,2};

  .
  .
  .

case WM_PAINT:
    hdc = BeginPaint(hwnd, &ps);

    // Determine whether the window is minimized.

    if (IsIconic(hwnd))
    {
        GetClientRect(hwnd, &rc);
        SetMapMode(hdc, MM_ANISOTROPIC);
        SetWindowExtEx(hdc, 100, 100, NULL);
        SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);
        Polyline(hdc, aptStar, 6);
    }
    else
    {
        TextOut(hdc, 0,0, "Hello, Windows!", 15);
    }
    EndPaint(hwnd, &ps);
    return 0L;

You set the class icon to NULL by setting the hIcon member of the WNDCLASS structure to NULL before calling the RegisterClass function for the window class.


Drawing a Custom Window Background

You can draw your own window background rather than having the system draw it for you. Most applications specify a brush handle or system color value for the class background brush when registering the window class; the system uses the brush or color to draw the background. If you set the class background brush to NULL, however, the system sends a WM_ERASEBKGND message to your window procedure whenever the window background must be drawn, letting you draw a custom background.

In the following example, the window procedure draws a large checkerboard pattern that fits neatly in the window. The procedure fills the client area with a white brush and then draws thirteen 20-by-20 rectangles using a gray brush. The display device context to use when drawing the background is specified in the wParam parameter for the message.

HBRUSH hbrWhite, hbrGray;

  .
  .
  .

case WM_CREATE:
    hbrWhite = GetStockObject(WHITE_BRUSH);
    hbrGray  = GetStockObject(GRAY_BRUSH);
    return 0L;

case WM_ERASEBKGND:
    hdc = (HDC) wParam;
    GetClientRect(hwnd, &rc);
    SetMapMode(hdc, MM_ANISOTROPIC);
    SetWindowExtEx(hdc, 100, 100, NULL);
    SetViewportExtEx(hdc, rc.right, rc.bottom, NULL);
    FillRect(hdc, &rc, hbrWhite);

    for (i = 0; i < 13; i++)
    {
        x = (i * 40) % 100;
        y = ((i * 40) / 100) * 20;
        SetRect(&rc, x, y, x + 20, y + 20);
        FillRect(hdc, &rc, hbrGray);
    }
  return 1L;

If the application draws its own minimized window, the system also sends the WM_ERASEBKGND message to the window procedure to draw the background for the minimized window. You can use the same technique used by WM_PAINT to determine whether the window is minimized — that is, call the IsIconic function and check for the return value TRUE.


Using the GetDC Function

You use the GetDC function to carry out drawing that must occur instantly rather than when a WM_PAINT message is processing. Such drawing is usually in response to an action by the user, such as making a selection or drawing with the mouse. In such cases, the user should receive instant feedback and must not be forced to stop selecting or drawing in order for the application to display the result. The following sections show how to use GetDC to draw in a window:

  • Drawing with the Mouse
  • Drawing at Timed Intervals


Drawing with the Mouse

You can permit the user to draw lines with the mouse by having your window procedure draw while processing the WM_MOUSEMOVE message. The system sends the WM_MOUSEMOVE message to the window procedure whenever the user moves the cursor within the window. To draw lines, the window procedure can retrieve a display device context and draw a line in the window between the current and previous cursor positions.

In the following example, the window procedure prepares for drawing when the user presses and holds the left mouse button (sending the WM_LBUTTONDOWN message). As the user moves the cursor within the window, the window procedure receives a series of WM_MOUSEMOVE messages. For each message, the window procedure draws a line connecting the previous position and the current position. To draw the line, the procedure uses GetDC to retrieve a display device context; then, as soon as drawing is complete and before returning from the message, the procedure uses the ReleaseDC function to release the display device context. As soon as the user releases the mouse button, the window procedure clears the flag, and the drawing stops (which sends the WM_LBUTTONUP message).

BOOL fDraw = FALSE;
POINT ptPrevious;

  .
  .
  .

case WM_LBUTTONDOWN:
    fDraw = TRUE;
    ptPrevious.x = LOWORD(lParam);
    ptPrevious.y = HIWORD(lParam);
    return 0L;

case WM_LBUTTONUP:
    if (fDraw)
    {
        hdc = GetDC(hwnd);
        MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);
        LineTo(hdc, LOWORD(lParam), HIWORD(lParam));
        ReleaseDC(hwnd, hdc);
    }
    fDraw = FALSE;
    return 0L;

case WM_MOUSEMOVE:
    if (fDraw)
    {
        hdc = GetDC(hwnd);
        MoveToEx(hdc, ptPrevious.x, ptPrevious.y, NULL);
        LineTo(hdc, ptPrevious.x = LOWORD(lParam),
          ptPrevious.y = HIWORD(lParam));
        ReleaseDC(hwnd, hdc);
    }
    return 0L;

An application that enables drawing, as in this example, typically records either the points or lines so that the lines can be redrawn whenever the window is updated. Drawing applications often use a memory device context and an associated bitmap to store lines that were drawn by using a mouse.


Drawing at Timed Intervals

You can draw at timed intervals by creating a timer with the SetTimer function. By using a timer to send WM_TIMER messages to the window procedure at regular intervals, an application can carry out simple animation in the client area while other applications continue running.

In the following example, the application bounces a star from side to side in the client area. Each time the window procedure receives a WM_TIMER message, the procedure erases the star at the current position, calculates a new position, and draws the star within the new position. The procedure starts the timer by calling SetTimer while processing the WM_CREATE message.

RECT rcCurrent = {0,0,20,20};
POINT aptStar[6] = {10,1, 1,19, 19,6, 1,6, 19,19, 10,1};
int X = 2, Y = -1, idTimer = -1;
BOOL fVisible = FALSE;
HDC hdc;

LRESULT APIENTRY WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    RECT rc;

    switch (message)
    {
        case WM_CREATE:

            // Calculate the starting point.

            GetClientRect(hwnd, &rc);
            OffsetRect(&rcCurrent, rc.right / 2, rc.bottom / 2);

            // Initialize the private DC.

            hdc = GetDC(hwnd);
            SetViewportOrgEx(hdc, rcCurrent.left,
                rcCurrent.top, NULL);
            SetROP2(hdc, R2_NOT);

            // Start the timer.

            SetTimer(hwnd, idTimer = 1, 10, NULL);
            return 0L;

        case WM_DESTROY:
            KillTimer(hwnd, 1);
            PostQuitMessage(0);
            return 0L;

        case WM_SIZE:
            switch (wParam)
            {
                case SIZE_MINIMIZED:

                    / Stop the timer if the window is minimized.

                    KillTimer(hwnd, 1);
                    idTimer = -1;
                    break;

                case SIZE_RESTORED:

                    // Move the star back into the client area
                    // if necessary.

                    if (rcCurrent.right > (int) LOWORD(lParam))
                    {
                        rcCurrent.left =
                            (rcCurrent.right =
                                (int) LOWORD(lParam)) - 20;
                    }
                    if (rcCurrent.bottom > (int) HIWORD(lParam))
                    {
                        rcCurrent.top =
                            (rcCurrent.bottom =
                                (int) HIWORD(lParam)) - 20;
                    }

                    // Fall through to the next case.

                case SIZE_MAXIMIZED:

                    // Start the timer if it had been stopped.

                    if (idTimer == -1)
                        SetTimer(hwnd, idTimer = 1, 10, NULL);
                    break;
            }
            return 0L;

        case WM_TIMER:

            // Hide the star if it is visible.

            if (fVisible)
                Polyline(hdc, aptStar, 6);

            // Bounce the star off a side if necessary.

            GetClientRect(hwnd, &rc);
            if (rcCurrent.left + X < rc.left ||
                rcCurrent.right + X > rc.right)
                X = -X;
            if (rcCurrent.top + Y < rc.top ||
                rcCurrent.bottom + Y > rc.bottom)
                Y = -Y;

            // Show the star in its new position.

            OffsetRect(&rcCurrent, X, Y);
            SetViewportOrgEx(hdc, rcCurrent.left,
                rcCurrent.top, NULL);
            fVisible = Polyline(hdc, aptStar, 6);

            return 0L;

        case WM_ERASEBKGND:

            // Erase the star.

            fVisible = FALSE;
            return DefWindowProc(hwnd, message, wParam, lParam);

        case WM_PAINT:

            // Show the star if it is not visible. Use BeginPaint
            // to clear the update region.

            BeginPaint(hwnd, &ps);
            if (!fVisible)
                fVisible = Polyline(hdc, aptStar, 6);
            EndPaint(hwnd, &ps);
            return 0L;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}

This application uses a private device context to minimize the time required to prepare the device context for drawing. The window procedure retrieves and initializes the private device context when processing the WM_CREATE message, setting the binary raster operation mode to allow the star to be erased and drawn using the same call to the Polyline function. The window procedure also sets the viewport origin to allow the star to be drawn using the same set of points regardless of the star's position in the client area.

The application uses the WM_PAINT message to draw the star whenever the window must be updated. The window procedure draws the star only if it is not visible; that is, only if it has been erased by the WM_ERASEBKGND message. The window procedure intercepts the WM_ERASEBKGND message to set the fVisible variable, but passes the message to DefWindowProc so that the system can draw the window background.

The application uses the WM_SIZE message to stop the timer when the window is minimized and to restart the timer when the minimized window is restored. The window procedure also uses the message to update the current position of the star if the size of the window has been reduced so that the star is no longer in the client area. The application keeps track of the star's current position by using the structure specified by rcCurrent, which defines the bounding rectangle for the star. Keeping all corners of the rectangle in the client area keeps the star in the area. The window procedure initially centers the star in the client area when processing the WM_CREATE message.


Painting and Drawing Reference

The following elements are associated with painting and drawing:

  • Painting and Drawing Functions
  • Painting and Drawing Structures
  • Painting and Drawing Messages
  • Raster Operation Codes


Painting and Drawing Functions

The following functions are used with painting and drawing.

Function | Description
BeginPaint | Prepares a window for painting.
DrawAnimatedRects | Draws a rectangle and animates it to indicate icon or window activity.
DrawCaption | Draws a window caption.
DrawEdge | Draws one or more edges of rectangle.
DrawFocusRect | Draws a rectangle in the style that indicates the rectangle has the focus.
DrawFrameControl | Draws a frame control.
DrawState | Displays an image and applies a visual effect to indicate a state.
DrawStateProc | A callback function that renders a complex image for DrawState.
EndPaint | Marks the end of painting in a window.
ExcludeUpdateRgn | Prevents drawing within invalid areas of a window.
GdiFlush | Flushes the calling thread's current batch.
GdiGetBatchLimit | Returns the maximum number of function calls that can be accumulated in the calling thread's current batch.
GdiSetBatchLimit | Sets the maximum number of function calls that can be accumulated in the calling thread's current batch.
GetBkColor | Returns the background color for a device context.
GetBkMode | Returns the background mix mode for a device context.
GetBoundsRect | Gets the accumulated bounding rectangle for a device context.
GetROP2 | Gets the foreground mix mode of a device context.
GetUpdateRect | Gets the coordinates of the smallest rectangle that encloses the update region of a window.
GetUpdateRgn | Gets the update region of a window.
GetWindowDC | Gets the device context for a window, including title bar, menus, and scroll bars.
GetWindowRgn | Gets a copy of the window region of a window.
GetWindowRgnBox | Gets the dimensions of the tightest bounding rectangle for the window region of a window.
GrayString | Draws gray text at a location.
InvalidateRect | Adds a rectangle to a window's update region.
InvalidateRgn | Invalidates the client area within a region.
LockWindowUpdate | Disables or reenables drawing in a window.
OutputProc | A callback function used with the GrayString function. It is used to draw a string.
PaintDesktop | Fills the clipping region in a device context with a pattern.
RedrawWindow | Updates a region in a window's client area.
SetBkColor | Sets the background to a color value.
SetBkMode | Sets the background mix mode of a device context.
SetBoundsRect | Controls the accumulation of bounding rectangle information for a device context.
SetROP2 | Sets the foreground mix mode.
SetWindowRgn | Sets the window region of a window.
UpdateWindow | Updates the client area of a window.
ValidateRect | Validates the client area within a rectangle.
ValidateRgn | Validates the client area within a region.
WindowFromDC | Returns a handle to the window associated with a device context.


BeginPaint

The BeginPaint function prepares the specified window for painting and fills a PAINTSTRUCT structure with information about the painting.

HDC BeginPaint(
  HWND hwnd,            // handle to window
  LPPAINTSTRUCT lpPaint // paint information
);

Parameters

hwnd
[in] Handle to the window to be repainted.
lpPaint
[out] Pointer to the PAINTSTRUCT structure that will receive painting information.

Return Values

If the function succeeds, the return value is the handle to a display device context for the specified window.

If the function fails, the return value is NULL, indicating that no display device context is available.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The BeginPaint function automatically sets the clipping region of the device context to exclude any area outside the update region. The update region is set by the InvalidateRect or InvalidateRgn function and by the system after sizing, moving, creating, scrolling, or any other operation that affects the client area. If the update region is marked for erasing, BeginPaint sends a WM_ERASEBKGND message to the window.

An application should not call BeginPaint except in response to a WM_PAINT message. Each call to BeginPaint must have a corresponding call to the EndPaint function.

If the caret is in the area to be painted, BeginPaint automatically hides the caret to prevent it from being erased.

If the window's class has a background brush, BeginPaint uses that brush to erase the background of the update region before returning.

For an example, see Drawing in the Client Area.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, EndPaint, InvalidateRect, InvalidateRgn, PAINTSTRUCT, ValidateRect, ValidateRgn


DrawAnimatedRects

The DrawAnimatedRects function draws a wire-frame rectangle and animates it to indicate the opening of an icon or the minimizing or maximizing of a window.

BOOL DrawAnimatedRects(
  HWND hwnd,            // handle to clipping window
  int idAni,            // type of animation
  CONST RECT *lprcFrom, // rectangle coordinates (minimized)
  CONST RECT *lprcTo    // rectangle coordinates (restored)
);

Parameters

hwnd
[in] Handle to the window to which the rectangle is clipped. If this parameter is NULL, the working area of the screen is used.
idAni
[in] Specifies the type of animation. If you specify IDANI_CAPTION, the window caption will animate from the position specified by lprcFrom to the position specified by lprcTo. The effect is similar to minimizing or maximizing a window.
lprcFrom
[in] Pointer to a RECT structure specifying the location and size of the icon or minimized window. Coordinates are relative to the rectangle specified by the lprcClip parameter.
lprcTo
[in] Pointer to a RECT structure specifying the location and size of the restored window. Coordinates are relative to the rectangle specified by the lprcClip parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, RECT


DrawCaption

The DrawCaption function draws a window caption.

BOOL DrawCaption(
  HWND hwnd,    // handle to window
  HDC hdc,      // handle to device context
  LPCRECT lprc, // rectangle to draw into
  UINT uFlags   // drawing options
);

Parameters

hwnd
[in] Handle to a window that supplies text and an icon for the window caption.
hdc
[in] Handle to a device context. The function draws the window caption into this device context.
lprc
[in] Pointer to a RECT structure that specifies the bounding rectangle for the window caption.
uFlags
[in] Specifies drawing options. This parameter can be zero or more of the following values.
Value | Meaning
DC_ACTIVE | The function uses the colors that denote an active caption.
DC_BUTTONS | Whistler: If set, the function draws the buttons in the caption bar (to minimize, restore, or close an application).
DC_GRADIENT Windows 98/Me, Windows 2000 or later: When this flag is set, the function uses COLOR_GRADIENTACTIVECAPTION (if the DC_ACTIVE flag was set) or COLOR_GRADIENTINACTIVECAPTION for the title-bar color.

If this flag is not set, the function uses COLOR_ACTIVECAPTION or COLOR_INACTIVECAPTION for both colors.
DC_ICON | The function draws the icon when drawing the caption text.
DC_INBUTTON | The function draws the caption as a button.
DC_SMALLCAP | The function draws a small caption, using the current small caption font.
DC_TEXT | The function draws the caption text when drawing the caption.

If DC_SMALLCAP is specified, the function draws a normal window caption.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, RECT


DrawEdge

The DrawEdge function draws one or more edges of rectangle.

BOOL DrawEdge(
  HDC hdc,       // handle to device context
  LPRECT qrc,    // rectangle coordinates
  UINT edge,     // type of edge
  UINT grfFlags  // type of border
);

Parameters

hdc
[in] Handle to the device context.
qrc
[in/out] Pointer to a RECT structure that contains the logical coordinates of the rectangle.
edge
[in] Specifies the type of inner and outer edges to draw. This parameter must be a combination of one inner-border flag and one outer-border flag. The inner-border flags are as follows.
Value | Meaning
BDR_RAISEDINNER | Raised inner edge.
BDR_SUNKENINNER | Sunken inner edge.

The outer-border flags are as follows.
Value | Meaning
BDR_RAISEDOUTER | Raised outer edge.
BDR_SUNKENOUTER | Sunken outer edge.

Alternatively, the edge parameter can specify one of the following flags.
Value | Meaning
EDGE_BUMP | Combination of BDR_RAISEDOUTER and BDR_SUNKENINNER.
EDGE_ETCHED | Combination of BDR_SUNKENOUTER and BDR_RAISEDINNER.
EDGE_RAISED | Combination of BDR_RAISEDOUTER and BDR_RAISEDINNER.
EDGE_SUNKEN | Combination of BDR_SUNKENOUTER and BDR_SUNKENINNER.

grfFlags
[in] Specifies the type of border. This parameter can be a combination of the following values.
Value | Meaning
BF_ADJUST If this flag is passed, shrink the rectangle pointed to by the qrc parameter to exclude the edges that were drawn.

If this flag is not passed, then do not change the rectangle pointed to by the qrc parameter. .
BF_BOTTOM | Bottom of border rectangle.
BF_BOTTOMLEFT | Bottom and left side of border rectangle.
BF_BOTTOMRIGHT | Bottom and right side of border rectangle.
BF_DIAGONAL | Diagonal border.
BF_DIAGONAL_ENDBOTTOMLEFT | Diagonal border. The end point is the bottom-left corner of the rectangle; the origin is top-right corner.
BF_DIAGONAL_ENDBOTTOMRIGHT | Diagonal border. The end point is the bottom-right corner of the rectangle; the origin is top-left corner.
BF_DIAGONAL_ENDTOPLEFT | Diagonal border. The end point is the top-left corner of the rectangle; the origin is bottom-right corner.
BF_DIAGONAL_ENDTOPRIGHT | Diagonal border. The end point is the top-right corner of the rectangle; the origin is bottom-left corner.
BF_FLAT | Flat border.
BF_LEFT | Left side of border rectangle.
BF_MIDDLE | Interior of rectangle to be filled.
BF_MONO | One-dimensional border.
BF_RECT | Entire border rectangle.
BF_RIGHT | Right side of border rectangle.
BF_SOFT | Soft buttons instead of tiles.
BF_TOP | Top of border rectangle.
BF_TOPLEFT | Top and left side of border rectangle.
BF_TOPRIGHT | Top and right side of border rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, RECT


DrawFocusRect

The DrawFocusRect function draws a rectangle in the style used to indicate that the rectangle has the focus.

BOOL DrawFocusRect(
  HDC hDC,          // handle to device context
  CONST RECT* lprc  // logical coordinates
);

Parameters

hDC
[in] Handle to the device context.
lprc
[in] Pointer to a RECT structure that specifies the logical coordinates of the rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

DrawFocusRect works only in MM_TEXT mode.

Because DrawFocusRect is an XOR function, calling it a second time with the same rectangle removes the rectangle from the screen.

This function draws a rectangle that cannot be scrolled. To scroll an area containing a rectangle drawn by this function, call DrawFocusRect to remove the rectangle from the screen, scroll the area, and then call DrawFocusRect again to draw the rectangle in the new position.

Whistler: The focus rectangle can now be thicker than 1 pixel, so it is more visible for high-resolution, high-density displays and accessibility needs. This is handled by the SPI_SETFOCUSBORDERWIDTH and SPI_SETFOCUSBORDERHEIGHT in SystemParametersInfo.

For an example, see Creating an Owner-Drawn List Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, FrameRect, RECT


DrawFrameControl

The DrawFrameControl function draws a frame control of the specified type and style.

BOOL DrawFrameControl(
  HDC hdc,     // handle to device context
  LPRECT lprc, // bounding rectangle
  UINT uType,  // frame-control type
  UINT uState  // frame-control state
);

Parameters

hdc
[in] Handle to the device context of the window in which to draw the control.
lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the bounding rectangle for frame control.
uType
[in] Specifies the type of frame control to draw. This parameter can be one of the following values.
Value | Meaning
DFC_BUTTON | Standard button
DFC_CAPTION | Title bar
DFC_MENU | Menu bar
DFC_POPUPMENU | Windows 98/Me, Windows 2000 or later: Popup menu item.
DFC_SCROLL | Scroll bar

uState
[in] Specifies the initial state of the frame control. If uType is DFC_BUTTON, uState can be one of the following values.
Value | Meaning
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)

If uType is DFC_CAPTION, uState can be one of the following values.
Value | Meaning
DFCS_CAPTIONCLOSE | Close button
DFCS_CAPTIONHELP | Help button
DFCS_CAPTIONMAX | Maximize button
DFCS_CAPTIONMIN | Minimize button
DFCS_CAPTIONRESTORE | Restore button

If uType is DFC_MENU, uState can be one of the following values.
Value | Meaning
DFCS_MENUARROW | Submenu arrow
DFCS_MENUARROWRIGHT | Submenu arrow pointing left. This is used for the right-to-left cascading menus used with right-to-left languages such as Arabic or Hebrew.
DFCS_MENUBULLET | Bullet
DFCS_MENUCHECK | Check mark

If uType is DFC_SCROLL, uState can be one of the following values.
Value | Meaning
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_SCROLLSIZEGRIPRIGHT | Size grip in bottom-left corner of window. This is used with right-to-left languages such as Arabic or Hebrew.
DFCS_SCROLLUP | Up arrow of scroll bar

The following style can be used to adjust the bounding rectangle of the push button.
Value | Meaning
DFCS_ADJUSTRECT | Bounding rectangle is adjusted to exclude the surrounding edge of the push button.

One or more of the following values can be used to set the state of the control to be drawn.
Value | Meaning
DFCS_CHECKED | Button is checked.
DFCS_FLAT | Button has a flat border.
DFCS_HOT | Windows 98/Me, Windows 2000 or later: Button is hot-tracked.
DFCS_INACTIVE | Button is inactive (grayed).
DFCS_MONO | Button has a monochrome border.
DFCS_PUSHED | Button is pushed.
DFCS_TRANSPARENT | Windows 98/Me, Windows 2000 or later: The background remains untouched.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If uType is either DFC_MENU or DFC_BUTTON and uState is not DFCS_BUTTONPUSH, the frame control is a black-on-white mask (that is, a black frame control on a white background). In such cases, the application must pass a handle to a bitmap memory device control. The application can then use the associated bitmap as the hbmMask parameter to the MaskBlt function, or it can use the device context as a parameter to the BitBlt function using ROPs such as SRCAND and SRCINVERT.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, RECT


DrawState

The DrawState function displays an image and applies a visual effect to indicate a state, such as a disabled or default state.

BOOL DrawState(
  HDC hdc,                     // handle to device context
  HBRUSH hbr,                  // handle to brush
  DRAWSTATEPROC lpOutputFunc,  // callback function
  LPARAM lData,                // image information
  WPARAM wData,                // more image information
  int x,                       // horizontal location
  int y,                       // vertical location
  int cx,                      // image width
  int cy,                      // image height
  UINT fuFlags                 // image type and state
);

Parameters

hdc
[in] Handle to the device context to draw in.
hbr
[in] Handle to the brush used to draw the image, if the state specified by the fuFlags parameter is DSS_MONO. This parameter is ignored for other states.
lpOutputFunc
[in] Pointer to an application-defined callback function used to render the image. This parameter is required if the image type in fuFlags 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.
lData
[in] Specifies information about the image. The meaning of this parameter depends on the image type.
wData
[in] Specifies information about the image. The meaning of this parameter depends on the image type. It is, however, zero extended for use with the DrawStateProc function.
x
[in] Specifies the horizontal location at which to draw the image.
y
[in] Specifies the vertical location at which to draw the image.
cx
[in] Specifies the width of the image, in device units. This parameter is required if the image type is DST_COMPLEX. Otherwise, it can be zero to calculate the width of the image.
cy
[in] Specifies the height of the image, in device units. This parameter is required if the image type is DST_COMPLEX. Otherwise, it can be zero to calculate the height of the image.
fuFlags
[in] Specifies the image type and state. This parameter can be one of the following type values.
Value (type) | Meaning
DST_BITMAP | The image is a bitmap. The lData parameter is the bitmap handle. Note that the bitmap cannot already be selected into an existing device context.
DST_COMPLEX | The image is application defined. To render the image, DrawState calls the callback function specified by the lpOutputFunc parameter.
DST_ICON | The image is an icon. The lData parameter is the icon handle.
DST_PREFIXTEXT | The image is text that may contain an accelerator mnemonic. DrawState interprets the ampersand (&) prefix character as a directive to underscore the character that follows. The lData parameter is a pointer to the string, and the wData parameter specifies the length. If wData is zero, the string must be null-terminated.
DST_TEXT | The image is text. The lData parameter is a pointer to the string, and the wData parameter specifies the length. If wData is zero, the string must be null-terminated.

This parameter can also be one of the following state values.
Value (state) | Meaning
DSS_DISABLED | Embosses the image.
DSS_HIDEPREFIX | Windows 2000 or later: Ignores the ampersand (&) prefix character in the text, thus the letter that follows will not be underlined. This must be used with DST_PREFIXTEXT.
DSS_MONO | Draws the image using the brush specified by the hbr parameter.
DSS_NORMAL | Draws the image without any modification.
DSS_PREFIXONLY | Windows 2000 or later: Draws only the underline at the position of the letter after the ampersand (&) prefix character. No text in the string is drawn. This must be used with DST_PREFIXTEXT.
DSS_RIGHT | Aligns the text to the right.
DSS_UNION | Dithers the image.

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

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, DrawStateProc


DrawStateProc

The DrawStateProc function is an application-defined callback function that renders a complex image for the DrawState function. The DRAWSTATEPROC type defines a pointer to this callback function. DrawStateProc is a placeholder for the application-defined function name.

BOOL CALLBACK DrawStateProc(
  HDC hdc,       // handle to device context
  LPARAM lData,  // image information
  WPARAM wData,  // more image information
  int cx,        // image width
  int cy         // image height
);

Parameters

hdc
[in] Handle to the device context to draw in. The device context is a memory device context with a bitmap selected, the dimensions of which are at least as great as those specified by the cx and cy parameters.
lData
[in] Specifies information about the image, which the application passed to DrawState.
wData
[in] Specifies information about the image, which the application passed to DrawState.
cx
[in] Specifies the image width, in device units, as specified by the call to DrawState.
cy
[in] Specifies the image height, in device units, as specified by the call to DrawState.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, DrawState


EndPaint

The EndPaint function marks the end of painting in the specified window. This function is required for each call to the BeginPaint function, but only after painting is complete.

BOOL EndPaint(
  HWND hWnd,                  // handle to window
  CONST PAINTSTRUCT *lpPaint  // paint data
);

Parameters

hWnd
[in] Handle to the window that has been repainted.
lpPaint
[in] Pointer to a PAINTSTRUCT structure that contains the painting information retrieved by BeginPaint.

Return Values

The return value is always nonzero.

Remarks

If the caret was hidden by BeginPaint, EndPaint restores the caret to the screen.

For an example, see Drawing in the Client Area.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, PAINTSTRUCT


ExcludeUpdateRgn

The ExcludeUpdateRgn function prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region.

int ExcludeUpdateRgn(
  HDC hDC,    // handle to device context
  HWND hWnd   // handle to window
);

Parameters

hDC
[in] Handle to the device context associated with the clipping region.
hWnd
[in] Handle to the window to update.

Return Values

The return value specifies the complexity of the excluded region; it can be any one of the following values.

Value | Meaning
COMPLEXREGION | Region consists of more than one rectangle.
ERROR | An error occurred.
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, GetUpdateRect, GetUpdateRgn, UpdateWindow


GdiFlush

The GdiFlush function flushes the calling thread's current batch.

BOOL GdiFlush(VOID);

Parameters

This function has no parameters.

Return Values

If all functions in the current batch succeed, the return value is nonzero.

If not all functions in the current batch succeed, the return value is zero, indicating that at least one function returned an error.

Remarks

Batching enhances drawing performance by minimizing the amount of time needed to call GDI drawing functions that return Boolean values. The system accumulates the parameters for calls to these functions in the current batch and then calls the functions when the batch is flushed by any of the following means:

  • Calling the GdiFlush function.
  • Reaching or exceeding the batch limit set by the GdiSetBatchLimit function.
  • Filling the batching buffers.
  • Calling any GDI function that does not return a Boolean value.

The return value for GdiFlush applies only to the functions in the batch at the time GdiFlush is called. Errors that occur when the batch is flushed by any other means are never reported.

The GdiGetBatchLimit function returns the batch limit.

Note The batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

An application should call GdiFlush before a thread goes away if there is a possibility that there are pending function calls in the graphics batch queue. The system does not execute such batched functions when a thread goes away.

A multithreaded application that serializes access to GDI objects with a mutex must ensure flushing the GDI batch queue by calling GdiFlush as each thread releases ownership of the GDI object. This prevents collisions of the GDI objects (device contexts, metafiles, and so on).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GdiGetBatchLimit, GdiSetBatchLimit


GdiGetBatchLimit

The GdiGetBatchLimit function returns the maximum number of function calls that can be accumulated in the calling thread's current batch. The system flushes the current batch whenever this limit is exceeded.

DWORD GdiGetBatchLimit(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is the batch limit.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The batch limit is set by using the GdiSetBatchLimit function. Setting the limit to 1 effectively disables batching.

Only GDI drawing functions that return Boolean values can be batched; calls to any other GDI functions immediately flush the current batch. Exceeding the batch limit or calling the GdiFlush function also flushes the current batch.

When the system batches a function call, the function returns TRUE. The actual return value for the function is reported only if GdiFlush is used to flush the batch.

Note The batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GdiFlush, GdiSetBatchLimit


GdiSetBatchLimit

The GdiSetBatchLimit function sets the maximum number of function calls that can be accumulated in the calling thread's current batch. The system flushes the current batch whenever this limit is exceeded.

DWORD GdiSetBatchLimit(
  DWORD dwLimit   // batch limit
);

Parameters

dwLimit
[in] Specifies the batch limit to be set. A value of 0 sets the default limit. A value of 1 disables batching.

Return Values

If the function succeeds, the return value is the previous batch limit.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Only GDI drawing functions that return Boolean values can be accumulated in the current batch; calls to any other GDI functions immediately flush the current batch. Exceeding the batch limit or calling the GdiFlush function also flushes the current batch.

When the system accumulates a function call, the function returns TRUE to indicate it is in the batch. When the system flushes the current batch and executes the function for the second time, the return value is either TRUE or FALSE, depending on whether the function succeeds. This second return value is reported only if GdiFlush is used to flush the batch.

Note The batch limit is maintained for each thread separately. In order to completely disable batching, call GdiSetBatchLimit(1) during the initialization of each thread.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GdiFlush, GdiGetBatchLimit


GetBkColor

The GetBkColor function returns the current background color for the specified device context.

COLORREF GetBkColor(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context whose background color is to be returned.

Return Values

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

If the function fails, the return value is CLR_INVALID.

For an example, see Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetBkMode, SetBkColor, COLORREF


GetBkMode

The GetBkMode function returns the current background mix mode for a specified device context. The background mix mode of a device context affects text, hatched brushes, and pen styles that are not solid lines.

int GetBkMode(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context whose background mode is to be returned.

Return Values

If the function succeeds, the return value specifies the current background mix mode, either OPAQUE or TRANSPARENT.

If the function fails, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetBkColor, SetBkMode


GetBoundsRect

The GetBoundsRect function obtains the current accumulated bounding rectangle for a specified device context.

The system maintains an accumulated bounding rectangle for each application. An application can retrieve and set this rectangle.

UINT GetBoundsRect(
  HDC hdc,            // handle to device context
  LPRECT lprcBounds,  // bounding rectangle
  UINT flags          // function options
);

Parameters

hdc
[in] Handle to the device context whose bounding rectangle the function will return.
lprcBounds
[out] Pointer to the RECT structure that will receive the current bounding rectangle. The application's rectangle is returned in logical coordinates, and the bounding rectangle is returned in screen coordinates.
flags
[in] Specifies how the GetBoundsRect function will behave. This parameter can be the following value.
Value | Meaning
DCB_RESET | Clears the bounding rectangle after returning it. If this flag is not set, the bounding rectangle will not be cleared.

Return Values

The return value specifies the state of the accumulated bounding rectangle; it can be one of the following values.

Value | Meaning
0 | An error occurred. The specified device context handle is invalid.
DCB_DISABLE | Boundary accumulation is off.
DCB_ENABLE | Boundary accumulation is on.
DCB_RESET | The bounding rectangle is empty.
DCB_SET | The bounding rectangle is not empty.

Remarks

The DCB_SET value is a combination of the bit values DCB_ACCUMULATE and DCB_RESET. Applications that check the DCB_RESET bit to determine whether the bounding rectangle is empty must also check the DCB_ACCUMULATE bit. The bounding rectangle is empty only if the DCB_RESET bit is 1 and the DCB_ACCUMULATE bit is 0.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, SetBoundsRect


GetROP2

The GetROP2 function retrieves the foreground mix mode of the specified device context. The mix mode specifies how the pen or interior color and the color already on the screen are combined to yield a new color.

int GetROP2(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value specifies the foreground mix mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Following are the foreground mix modes.

Mix mode | Description
R2_BLACK | Pixel is always 0.
R2_COPYPEN | Pixel is the pen color.
R2_MASKNOTPEN | Pixel is a combination of the colors common to both the screen and the inverse of the pen.
R2_MASKPEN | Pixel is a combination of the colors common to both the pen and the screen.
R2_MASKPENNOT | Pixel is a combination of the colors common to both the pen and the inverse of the screen.
R2_MERGENOTPEN | Pixel is a combination of the screen color and the inverse of the pen color.
R2_MERGEPEN | Pixel is a combination of the pen color and the screen color.
R2_MERGEPENNOT | Pixel is a combination of the pen color and the inverse of the screen color.
R2_NOP | Pixel remains unchanged.
R2_NOT | Pixel is the inverse of the screen color.
R2_NOTCOPYPEN | Pixel is the inverse of the pen color.
R2_NOTMASKPEN | Pixel is the inverse of the R2_MASKPEN color.
R2_NOTMERGEPEN | Pixel is the inverse of the R2_MERGEPEN color.
R2_NOTXORPEN | Pixel is the inverse of the R2_XORPEN color.
R2_WHITE | Pixel is always 1.
R2_XORPEN | Pixel is a combination of the colors in the pen and in the screen, but not in both.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, SetROP2


GetUpdateRect

The GetUpdateRect function retrieves the coordinates of the smallest rectangle that completely encloses the update region of the specified window. GetUpdateRect retrieves the rectangle in logical coordinates. If there is no update region, GetUpdateRect retrieves an empty rectangle (sets all coordinates to zero).

BOOL GetUpdateRect(
  HWND hWnd,       // handle to window
  LPRECT lpRect,   // update rectangle coordinates
  BOOL bErase      // erase state
);

Parameters

hWnd
[in] Handle to the window with an update region that is to be retrieved.
lpRect
[out] Pointer to the RECT structure that receives the coordinates of the enclosing rectangle.

An application can set this parameter to NULL to determine whether an update region exists for the window. If this parameter is NULL, GetUpdateRect returns nonzero if an update region exists, and zero if one does not. This provides a simple and efficient means of determining whether a WM_PAINT message resulted from an invalid area.

bErase
[in] Specifies whether the background in the update region is to be erased. If this parameter is TRUE and the update region is not empty, GetUpdateRect sends a WM_ERASEBKGND message to the specified window to erase the background.

Return Values

If the update region is not empty, the return value is nonzero.

If there is no update region, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The update rectangle retrieved by the BeginPaint function is identical to that retrieved by GetUpdateRect.

BeginPaint automatically validates the update region, so any call to GetUpdateRect made immediately after the call to BeginPaint retrieves an empty update region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, GetUpdateRgn, InvalidateRect, RECT, UpdateWindow, ValidateRect


GetUpdateRgn

The GetUpdateRgn function retrieves the update region of a window by copying it into the specified region. The coordinates of the update region are relative to the upper-left corner of the window (that is, they are client coordinates).

int GetUpdateRgn(
  HWND hWnd,    // handle to window
  HRGN hRgn,    // handle to region
  BOOL bErase   // erase state
);

Parameters

hWnd
[in] Handle to the window with an update region that is to be retrieved.
hRgn
[in] Handle to the region to receive the update region.
bErase
[in] Specifies whether the window background should be erased and whether nonclient areas of child windows should be drawn. If this parameter is FALSE, no drawing is done.

Return Values

The return value indicates the complexity of the resulting region; it can be one of the following values.

Value | Meaning
COMPLEXREGION | Region consists of more than one rectangle.
ERROR | An error occurred.
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.

Remarks

The BeginPaint function automatically validates the update region, so any call to GetUpdateRgn made immediately after the call to BeginPaint retrieves an empty update region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions


GetWindowDC

The GetWindowDC function retrieves the device context (DC) for the entire window, including title bar, menus, and scroll bars. A window device context permits painting anywhere in a window, because the origin of the device context is the upper-left corner of the window instead of the client area.

GetWindowDC assigns default attributes to the window device context each time it retrieves the device context. Previous attributes are lost.

HDC GetWindowDC(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] Handle to the window with a device context that is to be retrieved. If this value is NULL, GetWindowDC retrieves the device context for the entire screen.

Windows 98/Me, Windows 2000 or later: If this parameter is NULL, GetWindowDC retrieves the device context for the primary display monitor. To get the device context for other display monitors, use the EnumDisplayMonitors and CreateDC functions.

Return Values

If the function succeeds, the return value is a handle to a device context for the specified window.

If the function fails, the return value is NULL, indicating an error or an invalid hWnd parameter.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

GetWindowDC is intended for special painting effects within a window's nonclient area. Painting in nonclient areas of any window is not recommended.

The GetSystemMetrics function can be used to retrieve the dimensions of various parts of the nonclient area, such as the title bar, menu, and scroll bars.

The GetDC function can be used to retrieve a device context for the entire screen.

After painting is complete, the ReleaseDC function must be called to release the device context. Not releasing the window device context has serious effects on painting requested by applications.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, GetDC, GetSystemMetrics, ReleaseDC


GetWindowRgn

The GetWindowRgn function obtains a copy of the window region of a window. The window region of a window is set by calling the SetWindowRgn function. The window region determines the area within the window where the system permits drawing. The system does not display any portion of a window that lies outside of the window region

int GetWindowRgn(
  HWND hWnd, // handle to window
  HRGN hRgn  // handle to window region
);

Parameters

hWnd
[in] Handle to the window whose window region is to be obtained.
hRgn
[in] Handle to the region which will be modified to represent the window region.

Return Values

The return value specifies the type of the region that the function obtains. It can be one of the following values.

Value | Meaning
NULLREGION | The region is empty.
SIMPLEREGION | The region is a single rectangle.
COMPLEXREGION | The region is more than one rectangle.
ERROR | The specified window does not have a region, or an error occurred while attempting to return the region. .

Remarks

The coordinates of a window's window region are relative to the upper-left corner of the window, not the client area of the window.

To set the window region of a window, call the SetWindowRgn function.

The following code shows how you pass in the handle of an existing region.

HRGN hrgn = CreateRectRgn(0,0,0,0);
int regionType = GetWindowRgn(hwnd, hrgn);
if (regionType != ERROR)
{
/* hrgn contains window region */
}
DeleteObject(hrgn); /* finished with region */

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, SetWindowRgn


GetWindowRgnBox

[This is preliminary documentation and subject to change.]

The GetWindowRgnBox function retrieves the dimensions of the tightest bounding rectangle for the window region of a window.

int GetWindowRgnBox(
  HWND hWnd, // handle to window
  LPRECT lprc   // rectangle
);

Parameters

hWnd
[in] Handle to the window.
lprc
[out] Pointer to a RECT structure that receives the rectangle dimensions.

Return Values

The return value specifies the type of the region that the function obtains. It can be one of the following values.

Value | Meaning
COMPLEXREGION | The region is more than one rectangle.
ERROR | The specified window does not have a region, or an error occurred while attempting to return the region.
NULLREGION | The region is empty.
SIMPLEREGION | The region is a single rectangle.

Remarks

The window region determines the area within the window where the system permits drawing. The system does not display any portion of a window that lies outside of the window region. The coordinates of a window's window region are relative to the upper-left corner of the window, not the client area of the window.

To set the window region of a window, call the SetWindowRgn function.

Requirements

Windows NT/2000 or later: Requires Whistler or later.
Windows 95/98/Me: Not supported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, SetWindowRgn, GetWindowRgn, GetClipBox, RECT


GrayString

The GrayString function draws gray text at the specified location. The function draws the text by copying it into a memory bitmap, graying the bitmap, and then copying the bitmap to the screen. The function grays the text regardless of the selected brush and background. GrayString uses the font currently selected for the specified device context.

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

BOOL GrayString(
  HDC hDC,                      // handle to DC
  HBRUSH hBrush,                // handle to the brush
  GRAYSTRINGPROC lpOutputFunc,  // callback function
  LPARAM lpData,                // application-defined data
  int nCount,                   // number of characters
  int X,                        // horizontal position
  int Y,                        // vertical position
  int nWidth,                   // width
  int nHeight                   // height
);

Parameters

hDC
[in] Handle to the device context.
hBrush
[in] Handle to the brush to be used for graying. If this parameter is NULL, the text is grayed with the same brush that was used to draw window text.
lpOutputFunc
[in] Pointer to the application-defined function that will draw the string, or, if TextOut is to be used to draw the string, it is a NULL pointer. For details, see the OutputProc callback function.
lpData
[in] Specifies a pointer to data to be passed to the output function. If the lpOutputFunc parameter is NULL, lpData must be a pointer to the string to be output.
nCount
[in] Specifies the number of characters to be output. If the nCount parameter is zero, GrayString calculates the length of the string (assuming lpData is a pointer to the string). If nCount is –1 and the function pointed to by lpOutputFunc returns FALSE, the image is shown but not grayed.
X
[in] Specifies the device x-coordinate of the starting position of the rectangle that encloses the string.
Y
[in] Specifies the device y-coordinate of the starting position of the rectangle that encloses the string.
nWidth
[in] Specifies the width, in device units, of the rectangle that encloses the string. If this parameter is zero, GrayString calculates the width of the area, assuming lpData is a pointer to the string.
nHeight
[in] Specifies the height, in device units, of the rectangle that encloses the string. If this parameter is zero, GrayString calculates the height of the area, assuming lpData is a pointer to the string.

Return Values

If the string is drawn, the return value is nonzero.

If either the TextOut function or the application-defined output function returned zero, or there was insufficient memory to create a memory bitmap for graying, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Without calling GrayString, an application can draw grayed strings on devices that support a solid gray color. The system color COLOR_GRAYTEXT is the solid-gray system color used to draw disabled text. The application can call the GetSysColor function to retrieve the color value of COLOR_GRAYTEXT. If the color is other than zero (black), the application can call the SetTextColor 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 gray the text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, DrawText, GetSysColor, OutputProc, SetTextColor, TabbedTextOut, TextOut


InvalidateRect

The InvalidateRect function adds a rectangle to the specified window's update region. The update region represents the portion of the window's client area that must be redrawn.

BOOL InvalidateRect(
  HWND hWnd,           // handle to window
  CONST RECT* lpRect,  // rectangle coordinates
  BOOL bErase          // erase state
);

Parameters

hWnd
[in] Handle to the window whose update region has changed. If this parameter is NULL, the system invalidates and redraws all windows, and sends the WM_ERASEBKGND and WM_NCPAINT messages to the window procedure before the function returns.
lpRect
[in] Pointer to a RECT structure that contains the client coordinates of the rectangle to be added to the update region. If this parameter is NULL, the entire client area is added to the update region.
bErase
[in] Specifies whether the background within the update region is to be erased when the update region is processed. If this parameter is TRUE, the background is erased when the BeginPaint function is called. If this parameter is FALSE, the background remains unchanged.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The invalidated areas accumulate in the update region until the region is processed when the next WM_PAINT message occurs or until the region is validated by using the ValidateRect or ValidateRgn function.

The system sends a WM_PAINT message to a window whenever its update region is not empty and there are no other messages in the application queue for that window.

If the bErase parameter is TRUE for any part of the update region, the background is erased in the entire region, not just in the specified part.

For an example, see Invalidating the Client Area.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, InvalidateRgn, RECT, ValidateRect, ValidateRgn, WM_ERASEBKGND, WM_NCPAINT, WM_PAINT


InvalidateRgn

The InvalidateRgn function invalidates the client area within the specified region by adding it to the current update region of a window. The invalidated region, along with all other areas in the update region, is marked for painting when the next WM_PAINT message occurs.

BOOL InvalidateRgn(
  HWND hWnd,    // handle to window
  HRGN hRgn,    // handle to region
  BOOL bErase   // erase state
);

Parameters

hWnd
[in] Handle to the window with an update region that is to be modified.
hRgn
[in] Handle to the region to be added to the update region. The region is assumed to have client coordinates. If this parameter is NULL, the entire client area is added to the update region.
bErase
[in] Specifies whether the background within the update region should be erased when the update region is processed. If this parameter is TRUE, the background is erased when the BeginPaint function is called. If the parameter is FALSE, the background remains unchanged.

Return Values

The return value is always nonzero.

Remarks

Invalidated areas accumulate in the update region until the next WM_PAINT message is processed or until the region is validated by using the ValidateRect or ValidateRgn function.

The system sends a WM_PAINT message to a window whenever its update region is not empty and there are no other messages in the application queue for that window.

The specified region must have been created by using one of the region functions.

If the bErase parameter is TRUE for any part of the update region, the background in the entire region is erased, not just in the specified part.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, InvalidateRect, ValidateRect, ValidateRgn, WM_PAINT


LockWindowUpdate

The LockWindowUpdate function disables or reenables drawing in the specified window. Only one window can be locked at a time.

BOOL LockWindowUpdate(
  HWND hWndLock   // handle to window
);

Parameters

hWndLock
[in] Specifies the window in which drawing will be disabled. If this parameter is NULL, drawing in the locked window is enabled.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero, indicating that an error occurred or another window was already locked.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

If an application with a locked window (or any locked child windows) calls the GetDC, GetDCEx, or BeginPaint function, the called function returns a device context with a visible region that is empty. This will occur until the application unlocks the window by calling LockWindowUpdate, specifying a value of NULL for hWndLock.

If an application attempts to draw within a locked window, the system records the extent of the attempted operation in a bounding rectangle. When the window is unlocked, the system invalidates the area within this bounding rectangle, forcing an eventual WM_PAINT message to be sent to the previously locked window and its child windows. If no drawing has occurred while the window updates were locked, no area is invalidated.

LockWindowUpdate does not make the specified window invisible and does not clear the WS_VISIBLE style bit.

A locked window cannot be moved.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, GetDC, GetDCEx, WM_PAINT


OutputProc

The OutputProc function is an application-defined callback function used with the GrayString function. It is used to draw a string. The GRAYSTRINGPROC type defines a pointer to this callback function. OutputProc is a placeholder for the application-defined or library-defined function name.

BOOL CALLBACK OutputProc(
  HDC hdc,        // handle to DC
  LPARAM lpData,  // string
  int cchData     // length of string
);

Parameters

hdc
[in] Handle to a device context with a bitmap of at least the width and height specified by the nWidth and nHeight parameters passed to GrayString.
lpData
[in] Pointer to the string to be drawn.
cchData
[in] Specifies the length, in characters, of the string.

Return Values

If it succeeds, the callback function should return TRUE.

If the function fails, the return value is FALSE.

Remarks

The callback function must draw an image relative to the coordinates (0,0).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GrayString


PaintDesktop

The PaintDesktop function fills the clipping region in the specified device context with the desktop pattern or wallpaper. The function is provided primarily for shell desktops.

BOOL PaintDesktop(
  HDC hdc  // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions


RedrawWindow

The RedrawWindow function updates the specified rectangle or region in a window's client area.

BOOL RedrawWindow(
  HWND hWnd,               // handle to window
  CONST RECT *lprcUpdate,  // update rectangle
  HRGN hrgnUpdate,         // handle to update region
  UINT flags               // array of redraw flags
);

Parameters

hWnd
[in] Handle to the window to be redrawn. If this parameter is NULL, the desktop window is updated.
lprcUpdate
[in] Pointer to a RECT structure containing the coordinates of the update rectangle. This parameter is ignored if the hrgnUpdate parameter identifies a region.
hrgnUpdate
[in] Handle to the update region. If both the hrgnUpdate and lprcUpdate parameters are NULL, the entire client area is added to the update region.
flags
[in] Specifies one or more redraw flags. This parameter can be used to invalidate or validate a window, control repainting, and control which windows are affected by RedrawWindow.

The following flags are used to invalidate the window.
Flag (invalidation) | Description
RDW_ERASE | Causes the window to receive a WM_ERASEBKGND message when the window is repainted. The RDW_INVALIDATE flag must also be specified; otherwise, RDW_ERASE has no effect.
RDW_FRAME | Causes any part of the nonclient area of the window that intersects the update region to receive a WM_NCPAINT message. The RDW_INVALIDATE flag must also be specified; otherwise, RDW_FRAME has no effect. The WM_NCPAINT message is typically not sent during the execution of RedrawWindow unless either RDW_UPDATENOW or RDW_ERASENOW is specified.
RDW_INTERNALPAINT | Causes a WM_PAINT message to be posted to the window regardless of whether any portion of the window is invalid.
RDW_INVALIDATE | Invalidates lprcUpdate or hrgnUpdate (only one may be non-NULL). If both are NULL, the entire window is invalidated.

The following flags are used to validate the window.
Flag (validation) | Description
RDW_NOERASE | Suppresses any pending WM_ERASEBKGND messages.
RDW_NOFRAME | Suppresses any pending WM_NCPAINT messages. This flag must be used with RDW_VALIDATE and is typically used with RDW_NOCHILDREN. RDW_NOFRAME should be used with care, as it could cause parts of a window to be painted improperly.
RDW_NOINTERNALPAINT | Suppresses any pending internal WM_PAINT messages. This flag does not affect WM_PAINT messages resulting from a non-NULL update area.
RDW_VALIDATE | Validates lprcUpdate or hrgnUpdate (only one may be non-NULL). If both are NULL, the entire window is validated. This flag does not affect internal WM_PAINT messages.

The following flags control when repainting occurs. RedrawWindow will not repaint unless one of these flags is specified.
Flag | Description
RDW_ERASENOW | Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT and WM_ERASEBKGND messages, if necessary, before the function returns. WM_PAINT messages are received at the ordinary time.
RDW_UPDATENOW | Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT, WM_ERASEBKGND, and WM_PAINT messages, if necessary, before the function returns.

By default, the windows affected by RedrawWindow depend on whether the specified window has the WS_CLIPCHILDREN style. Child windows that are not the WS_CLIPCHILDREN style are unaffected; non-WS_CLIPCHILDREN windows are recursively validated or invalidated until a WS_CLIPCHILDREN window is encountered. The following flags control which windows are affected by the RedrawWindow function.
Flag | Description
RDW_ALLCHILDREN | Includes child windows, if any, in the repainting operation.
RDW_NOCHILDREN | Excludes child windows, if any, from the repainting operation.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When RedrawWindow is used to invalidate part of the desktop window, the desktop window does not receive a WM_PAINT message. To repaint the desktop, an application uses the RDW_ERASE flag to generate a WM_ERASEBKGND message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetUpdateRect, GetUpdateRgn, InvalidateRect, InvalidateRgn, RECT, UpddateWindow


SetBkColor

The SetBkColor function sets the current background color to the specified color value, or to the nearest physical color if the device cannot represent the specified color value.

COLORREF SetBkColor(
  HDC hdc,           // handle to DC
  COLORREF crColor   // background color value
);

Parameters

hdc
[in] Handle to the device context.
crColor
[in] Specifies the new background color. To make a COLORREF value, use the RGB macro.

Return Values

If the function succeeds, the return value specifies the previous background color as a COLORREF value.

If the function fails, the return value is CLR_INVALID.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

This function fills the gaps between styled lines drawn using a pen created by the CreatePen function; it does not fill the gaps between styled lines drawn using a pen created by the ExtCreatePen function. The SetBKColor function also sets the background colors for TextOut and ExtTextOut.

If the background mode is OPAQUE, the background color is used to fill gaps between styled lines, gaps between hatched lines in brushes, and character cells. The background color is also used when converting bitmaps from color to monochrome and vice versa.

For an example, see Example of Owner-Drawn Menu Items.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, COLORREF, CreatePen, ExtCreatePen, GetBKColor, GetBkMode, SetBkMode


SetBkMode

The SetBkMode function sets the background mix mode of the specified device context. The background mix mode is used with text, hatched brushes, and pen styles that are not solid lines.

int SetBkMode(
  HDC hdc,      // handle to DC
  int iBkMode   // background mode
);

Parameters

hdc
[in] Handle to the device context.
iBkMode
[in] Specifies the background mode. This parameter can be one of the following values.
Value | Description
OPAQUE | Background is filled with the current background color before the text, hatched brush, or pen is drawn.
TRANSPARENT | Background remains untouched.

Return Values

If the function succeeds, the return value specifies the previous background mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The SetBkMode function affects the line styles for lines drawn using a pen created by the CreatePen function. SetBkMode does not affect lines drawn using a pen created by the ExtCreatePen function.

The iBkMode parameter can also be set to driver-specific values. GDI passes such values to the device driver and otherwise ignores them.

For an example, see Rotating Lines of Text.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, CreatePen, ExtCreatePen, GetBkMode


SetBoundsRect

The SetBoundsRect function controls the accumulation of bounding rectangle information for the specified device context. The system can maintain a bounding rectangle for all drawing operations. An application can examine and set this rectangle. The drawing boundaries are useful for invalidating bitmap caches.

UINT SetBoundsRect(
  HDC hdc,                 // handle to DC
  CONST RECT *lprcBounds,  // bounding rectangle
  UINT flags               // rectangle combination option
);

Parameters

hdc
[in] Handle to the device context for which to accumulate bounding rectangles.
lprcBounds
[in] Pointer to a RECT structure used to set the bounding rectangle. Rectangle dimensions are in logical coordinates. This parameter can be NULL.
flags
[in] Specifies how the new rectangle will be combined with the accumulated rectangle. This parameter can be one of more of the following values.
Value | Description
DCB_ACCUMULATE | Adds the rectangle specified by the lprcBounds parameter to the bounding rectangle (using a rectangle union operation). Using both DCB_RESET and DCB_ACCUMULATE sets the bounding rectangle to the rectangle specified by the lprcBounds parameter.
DCB_DISABLE | Turns off boundary accumulation.
DCB_ENABLE | Turns on boundary accumulation, which is disabled by default.
DCB_RESET | Clears the bounding rectangle.

Return Values

If the function succeeds, the return value specifies the previous state of the bounding rectangle. This state can be a combination of the following values.

Value | Meaning
DCB_DISABLE | Boundary accumulation is off.
DCB_ENABLE | Boundary accumulation is on. DCB_ENABLE and DCB_DISABLE are mutually exclusive.
DCB_RESET | Bounding rectangle is empty.
DCB_SET | Bounding rectangle is not empty. DCB_SET and DCB_RESET are mutually exclusive.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The DCB_SET value is a combination of the bit values DCB_ACCUMULATE and DCB_RESET. Applications that check the DCB_RESET bit to determine whether the bounding rectangle is empty must also check the DCB_ACCUMULATE bit. The bounding rectangle is empty only if the DCB_RESET bit is 1 and the DCB_ACCUMULATE bit is 0.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetBoundsRect, RECT


SetROP2

The SetROP2 function sets the current foreground mix mode. GDI uses the foreground mix mode to combine pens and interiors of filled objects with the colors already on the screen. The foreground mix mode defines how colors from the brush or pen and the colors in the existing image are to be combined.

int SetROP2(
  HDC hdc,         // handle to DC
  int fnDrawMode   // drawing mode
);

Parameters

hdc
[in] Handle to the device context.
fnDrawMode
[in] Specifies the mix mode. This parameter can be one of the following values.
Mix mode | Description
R2_BLACK | Pixel is always 0.
R2_COPYPEN | Pixel is the pen color.
R2_MASKNOTPEN | Pixel is a combination of the colors common to both the screen and the inverse of the pen.
R2_MASKPEN | Pixel is a combination of the colors common to both the pen and the screen.
R2_MASKPENNOT | Pixel is a combination of the colors common to both the pen and the inverse of the screen.
R2_MERGENOTPEN | Pixel is a combination of the screen color and the inverse of the pen color.
R2_MERGEPEN | Pixel is a combination of the pen color and the screen color.
R2_MERGEPENNOT | Pixel is a combination of the pen color and the inverse of the screen color.
R2_NOP | Pixel remains unchanged.
R2_NOT | Pixel is the inverse of the screen color.
R2_NOTCOPYPEN | Pixel is the inverse of the pen color.
R2_NOTMASKPEN | Pixel is the inverse of the R2_MASKPEN color.
R2_NOTMERGEPEN | Pixel is the inverse of the R2_MERGEPEN color.
R2_NOTXORPEN | Pixel is the inverse of the R2_XORPEN color.
R2_WHITE | Pixel is always 1.
R2_XORPEN | Pixel is a combination of the colors in the pen and in the screen, but not in both.

Return Values

If the function succeeds, the return value specifies the previous mix mode.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

Mix modes define how GDI combines source and destination colors when drawing with the current pen. The mix modes are binary raster operation codes, representing all possible Boolean functions of two variables, using the binary operations AND, OR, and XOR (exclusive OR), and the unary operation NOT. The mix mode is for raster devices only; it is not available for vector devices.

For an example, see Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetROP2


SetWindowRgn

The SetWindowRgn function sets the window region of a window. The window region determines the area within the window where the system permits drawing. The system does not display any portion of a window that lies outside of the window region

int SetWindowRgn(
  HWND hWnd,     // handle to window
  HRGN hRgn,     // handle to region
  BOOL bRedraw   // window redraw option
);

Parameters

hWnd
[in] Handle to the window whose window region is to be set.
hRgn
[in] Handle to a region. The function sets the window region of the window to this region.

If hRgn is NULL, the function sets the window region to NULL.

bRedraw
[in] Specifies whether the system redraws the window after setting the window region. If bRedraw is TRUE, the system does so; otherwise, it does not.

Typically, you set bRedraw to TRUE if the window is visible.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

When this function is called, the system sends the WM_WINDOWPOSCHANGING and WM_WINDOWPOSCHANGED messages to the window.

The coordinates of a window's window region are relative to the upper-left corner of the window, not the client area of the window.

After a successful call to SetWindowRgn, the system owns the region specified by the region handle hRgn. The system does not make a copy of the region. Thus, you should not make any further function calls with this region handle. In particular, do not delete this region handle. The system deletes the region handle when it no longer needed.

To obtain the window region of a window, call the GetWindowRgn function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetWindowRgn, WM_WINDOWPOSCHANGING


UpdateWindow

The UpdateWindow function updates the client area of the specified window by sending a WM_PAINT message to the window if the window's update region is not empty. The function sends a WM_PAINT message directly to the window procedure of the specified window, bypassing the application queue. If the update region is empty, no message is sent.

BOOL UpdateWindow(
  HWND hWnd   // handle to window
);

Parameters

hWnd
[in] Handle to the window to be updated.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example, see Drawing in the Client Area.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, ExcludeUpdateRgn, GetUpdateRect, GetUpdateRgn, InvalidateRect, InvalidateRgn, WM_PAINT


ValidateRect

The ValidateRect function validates the client area within a rectangle by removing the rectangle from the update region of the specified window.

BOOL ValidateRect(
  HWND hWnd,          // handle to window
  CONST RECT *lpRect  // validation rectangle coordinates
);

Parameters

hWnd
[in] Handle to the window whose update region is to be modified. If this parameter is NULL, the system invalidates and redraws all windows and sends the WM_ERASEBKGND and WM_NCPAINT messages to the window procedure before the function returns.
lpRect
[in] Pointer to a RECT structure that contains the client coordinates of the rectangle to be removed from the update region. If this parameter is NULL, the entire client area is removed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The BeginPaint function automatically validates the entire client area. Neither the ValidateRect nor ValidateRgn function should be called if a portion of the update region must be validated before the next WM_PAINT message is generated.

The system continues to generate WM_PAINT messages until the current update region is validated.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, InvalidateRect, InvalidateRgn, RECT, ValidateRgn, WM_PAINT


ValidateRgn

The ValidateRgn function validates the client area within a region by removing the region from the current update region of the specified window.

BOOL ValidateRgn(
  HWND hWnd,  // handle to window
  HRGN hRgn   // handle to region
);

Parameters

hWnd
[in] Handle to the window whose update region is to be modified.
hRgn
[in] Handle to a region that defines the area to be removed from the update region. If this parameter is NULL, the entire client area is removed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The specified region must have been created by a region function. The region coordinates are assumed to be client coordinates.

The BeginPaint function automatically validates the entire client area. Neither the ValidateRect nor ValidateRgn function should be called if a portion of the update region must be validated before the next WM_PAINT message is generated.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, BeginPaint, ExcludeUpdateRgn, InvalidateRect, InvalidateRgn, ValidateRect, WM_PAINT


WindowFromDC

The WindowFromDC function returns a handle to the window associated with the specified display device context (DC). Output functions that use the specified device context draw into this window.

HWND WindowFromDC(
  HDC hDC   // handle to window
);

Parameters

hDC
[in] Handle to the device context from which a handle for the associated window is to be retrieved.

Return Values

The return value is a handle to the window associated with the specified DC. If no window is associated with the specified DC, the return value is NULL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Functions, GetDC, GetDCEx, GetWindowDC


Painting and Drawing Structures

The following structure is used with painting and drawing.

PAINTSTRUCT


PAINTSTRUCT

The PAINTSTRUCT structure contains information for an application. This information can be used to paint the client area of a window owned by that application.

typedef struct tagPAINTSTRUCT {
  HDC  hdc;
  BOOL fErase;
  RECT rcPaint;
  BOOL fRestore;
  BOOL fIncUpdate;
  BYTE rgbReserved[32];
} PAINTSTRUCT, *PPAINTSTRUCT;

Members

hdc
Handle to the display DC to be used for painting.
fErase
Specifies whether the background must be erased. This value is nonzero if the application should erase the background. The application is responsible for erasing the background if a window class is created without a background brush. For more information, see the description of the hbrBackground member of the WNDCLASS structure.
rcPaint
Specifies a RECT structure that specifies the upper left and lower right corners of the rectangle in which the painting is requested.
fRestore
Reserved; used internally by the system.
fIncUpdate
Reserved; used internally by the system.
rgbReserved
Reserved; used internally by the system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Structures, BeginPaint, RECT, WNDCLASS


Painting and Drawing Messages

The following messages are used with painting and drawing.

WM_DISPLAYCHANGE
WM_ERASEBKGND
WM_ICONERASEBKGND
WM_NCPAINT
WM_PAINT
WM_PAINTICON
WM_PRINT
WM_PRINTCLIENT
WM_SETREDRAW
WM_SYNCPAINT


WM_DISPLAYCHANGE

The WM_DISPLAYCHANGE message is sent to all windows when the display resolution has changed.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_DISPLAYCHANGE
  WPARAM wParam,   // image depth
  LPARAM lParam    // screen resolution
);

Parameters

wParam
Specifies the new image depth of the display, in bits per pixel.
lParam
The low-order word specifies the horizontal resolution of the screen.

The high-order word specifies the vertical resolution of the screen.

Remarks

This message is only sent to top-level windows. For all other windows it is posted.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, , HIWORD, LOWORD


WM_NCPAINT

The WM_NCPAINT message is sent to a window when its frame must be painted.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_NCPAINT
  WPARAM wParam,   // handle to update region (HRGN)
  LPARAM lParam    // not used
);

Parameters

wParam
Handle to the update region of the window. The update region is clipped to the window frame. When wParam is 1, the entire window frame needs to be updated.
lParam
This parameter is not used.

Return Values

An application returns zero if it processes this message.

Remarks

The DefWindowProc function paints the window frame.

An application can intercept the WM_NCPAINT message and paint its own custom window frame. The clipping region for a window is always rectangular, even if the shape of the frame is altered.

The wParam value can be passed to GetDCEx as in the following example.

case WM_NCPAINT:
{
    HDC hdc;
    hdc = GetDCEx(hwnd, (HRGN)wParam, DCX_WINDOW|DCX_INTERSECTRGN);
    // Paint into this DC
    ReleaseDC(hwnd, hdc);
}

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, DefWindowProc, GetWindowDC, WM_PAINT GetDCEx


WM_PAINT

The WM_PAINT message is sent when the system or another application makes a request to paint a portion of an application's window. The message is sent when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage function when the application obtains a WM_PAINT message by using the GetMessage or PeekMessage function.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PAINT
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

wParam
This parameter is not used.
lParam
This parameter is not used.

Return Values

An application returns zero if it processes this message.

Remarks

The WM_PAINT message is generated by the system and should not be sent by an application. To force a window to draw into a specific device context, use the WM_PRINT or WM_PRINTCLIENT message. Note that this requires the target window to support the WM_PRINTCLIENT message. Most common controls support the WM_PRINTCLIENT message.

The DefWindowProc function validates the update region. The function may also send the WM_NCPAINT message to the window procedure if the window frame must be painted and send the WM_ERASEBKGND message if the window background must be erased.

The system sends this message when there are no other messages in the application's message queue. DispatchMessage determines where to send the message; GetMessage determines which message to dispatch. GetMessage returns the WM_PAINT message when there are no other messages in the application's message queue, and DispatchMessage sends the message to the appropriate window procedure.

A window may receive internal paint messages as a result of calling RedrawWindow with the RDW_INTERNALPAINT flag set. In this case, the window may not have an update region. An application should call the GetUpdateRect function to determine whether the window has an update region. If GetUpdateRect returns zero, the application should not call the BeginPaint and EndPaint functions.

An application must check for any necessary internal painting by looking at its internal data structures for each WM_PAINT message, because a WM_PAINT message may have been caused by both a non-NULL update region and a call to RedrawWindow with the RDW_INTERNALPAINT flag set.

The system sends an internal WM_PAINT message only once. After an internal WM_PAINT message is returned from GetMessage or PeekMessage or is sent to a window by UpdateWindow, the system does not post or send further WM_PAINT messages until the window is invalidated or until RedrawWindow is called again with the RDW_INTERNALPAINT flag set.

For some common controls, the default WM_PAINT message processing checks the wParam parameter. If wParam is non-NULL, the control assumes that the value is an HDC and paints using that device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, BeginPaint, DefWindowProc, DispatchMessage, EndPaint, GetMessage, GetUpdateRect, PeekMessage, RedrawWindow, UpdateWindow, WM_ERASEBKGND, WM_NCPAINT, WM_PRINT , WM_PRINTCLIENT


WM_PRINT

The WM_PRINT message is sent to a window to request that it draw itself in the specified device context, most commonly in a printer device context.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PRINT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // drawing options
);

Parameters

wParam
Handle to the device context to draw in.
lParam
Specifies the drawing options. This parameter can be one or more of the following values.
Value | Meaning
PRF_CHECKVISIBLE | Draws the window only if it is visible.
PRF_CHILDREN | Draws all visible children windows.
PRF_CLIENT | Draws the client area of the window.
PRF_ERASEBKGND | Erases the background before drawing the window.
PRF_NONCLIENT | Draws the nonclient area of the window.
PRF_OWNED | Draws all owned windows.

Remarks

The DefWindowProc function processes this message based on which drawing option is specified: if PRF_CHECKVISIBLE is specified and the window is not visible, do nothing, if PRF_NONCLIENT is specified, draw the nonclient area in the specified device context, if PRF_ERASEBKGND is specified, send the window a WM_ERASEBKGND message, if PRF_CLIENT is specified, send the window a WM_PRINTCLIENT message, if PRF_CHILDREN is set, send each visible child window a WM_PRINT message, if PRF_OWNED is set, send each visible owned window a WM_PRINT message.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, DefWindowProc, WM_ERASEBKGND, WM_PRINTCLIENT


WM_PRINTCLIENT

The WM_PRINTCLIENT message is sent to a window to request that it draw its client area in the specified device context, most commonly in a printer device context.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_PRINTCLIENT
  WPARAM wParam,   // handle to DC (HDC)
  LPARAM lParam    // drawing options
);

Parameters

wParam
Handle to the device context to draw in.
lParam
Specifies drawing options. This parameter can be one or more of the following values.
Value | Meaning
PRF_CHECKVISIBLE | Draws the window only if it is visible.
PRF_CHILDREN | Draws all visible children windows.
PRF_CLIENT | Draws the client area of the window.
PRF_ERASEBKGND | Erases the background before drawing the window.
PRF_NONCLIENT | Draws the nonclient area of the window.
PRF_OWNED | Draws all owned windows.

Remarks

A window can process this message in much the same manner as WM_PAINT, except that BeginPaint and EndPaint need not be called (a device context is provided), and the window should draw its entire client area rather than just the invalid region.

Windows that can be used anywhere in the system, such as controls, should process this message. It is probably worthwhile for other windows to process this message as well because it is relatively easy to implement.

The AnimateWindow function requires that the window being animated implement the WM_PRINTCLIENT message.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, AnimateWindow, BeginPaint, EndPaint, WM_PAINT


WM_SETREDRAW

An application sends the WM_SETREDRAW message to a window to allow changes in that window to be redrawn or to prevent changes in that window from being redrawn.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_SETREDRAW,             // message to send
  (WPARAM) wParam,          // redraw state
  (LPARAM) lParam          // not used; must be zero
);

Parameters

wParam
Specifies the redraw state. If this parameter is TRUE, the content can be redrawn after a change. If this parameter is FALSE, the content cannot be redrawn after a change.
lParam
This parameter is not used.

Return Values

An application returns zero if it processes this message.

Remarks

This message can be useful if an application must add several items to a list box. The application can call this message with wParam set to FALSE, add the items, and then call the message again with wParam set to TRUE. Finally, the application can call the InvalidateRect function to cause the list box to be repainted.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, InvalidateRect


WM_SYNCPAINT

The WM_SYNCPAINT message is used to synchronize painting while avoiding linking independent GUI threads.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SYNCPAINT
  WPARAM wParam,   // not used
  LPARAM lParam    // not used
);

Parameters

This message has no parameters.

Return Values

An application returns zero if it processes this message.

Remarks

When a window has been hidden, shown, moved, or sized, the system may determine that it is necessary to send a WM_SYNCPAINT message to the top-level windows of other threads. Applications must pass WM_SYNCPAINT to DefWindowProc for processing. The DefWindowProc function will send a WM_NCPAINT message to the window procedure if the window frame must be painted and send a WM_ERASEBKGND message if the window background must be erased.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, DefWindowProc, GetDCEx, GetWindowDC, WM_PAINT


Raster Operation Codes

Raster-operation codes define how the graphics device interface (GDI) combines the bits from the selected pen with the bits in the destination bitmap.

This overview lists and describes the binary and ternary raster operations used by GDI. A binary raster operation involves two operands: a pen and a destination bitmap. A ternary raster operation involves three operands: a source bitmap, a brush, and a destination bitmap. Both binary and ternary raster operations use Boolean operators.


Binary Raster Operations

This section lists the binary raster-operation codes used by the GetROP2 and SetROP2 functions. Raster-operation codes define how GDI combines the bits from the selected pen with the bits in the destination bitmap.

Each raster-operation code represents a Boolean operation in which the values of the pixels in the selected pen and the destination bitmap are combined. The following are the two operands used in these operations.

Operand | Meaning
P | Selected pen
D | Destination bitmap

The Boolean operators used in these operations follow.

Operator | Meaning
a | Bitwise AND
n | Bitwise NOT (inverse)
o | Bitwise OR
x | Bitwise exclusive OR (XOR)

All Boolean operations are presented in reverse Polish notation. For example, the following operation replaces the values of the pixels in the destination bitmap with a combination of the pixel values of the pen and the selected brush:

DPo

Each raster-operation code is a 32-bit integer whose high-order word is a Boolean operation index and whose low-order word is the operation code. The 16-bit operation index is a zero-extended 8-bit value that represents all possible outcomes resulting from the Boolean operation on two parameters (in this case, the pen and destination values). For example, the operation indexes for the DPo and DPan operations are shown in the following list.

P | D | DPo | Dpan
0 | 0 | 0 | 1
0 | 1 | 1 | 1
1 | 0 | 1 | 1
1 | 1 | 1 | 0

The following list outlines the drawing modes and the Boolean operations that they represent.

Raster operation | Boolean operation
R2_BLACK | 0
R2_COPYPEN | P
R2_MASKNOTPEN | DPna
R2_MASKPEN | DPa
R2_MASKPENNOT | PDna
R2_MERGENOTPEN | DPno
R2_MERGEPEN | DPo
R2_MERGEPENNOT | PDno
R2_NOP | D
R2_NOT | Dn
R2_NOTCOPYPEN | Pn
R2_NOTMASKPEN | DPan
R2_NOTMERGEPEN | DPon
R2_NOTXORPEN | DPxn
R2_WHITE | 1
R2_XORPEN | DPx

For a monochrome device, GDI maps the value zero to black and the value 1 to white. If an application attempts to draw with a black pen on a white destination by using the available binary raster operations, the following results occur.

Raster operation | Result
R2_BLACK | Visible black line
R2_COPYPEN | Visible black line
R2_MASKNOTPEN | No visible line
R2_MASKPEN | Visible black line
R2_MASKPENNOT | Visible black line
R2_MERGENOTPEN | No visible line
R2_MERGEPEN | Visible black line
R2_MERGEPENNOT | Visible black line
R2_NOP | No visible line
R2_NOT | Visible black line
R2_NOTCOPYPEN | No visible line
R2_NOTMASKPEN | No visible line
R2_NOTMERGEPEN | Visible black line
R2_NOTXORPEN | Visible black line
R2_WHITE | No visible line
R2_XORPEN | No visible line

For a color device, GDI uses RGB values to represent the colors of the pen and the destination. An RGB color value is a long integer that contains a red, a green, and a blue color field, each specifying the intensity of the specified color. Intensities range from 0 through 255. The values are packed in the three low-order bytes of the long integer. The color of a pen is always a solid color, but the color of the destination may be a mixture of any two or three colors. If an application attempts to draw with a white pen on a blue destination by using the available binary raster operations, the following results occur.

Raster operation | Result
R2_BLACK | Visible black line
R2_COPYPEN | Visible white line
R2_MASKNOTPEN | Visible black line
R2_MASKPEN | Invisible blue line
R2_MASKPENNOT | Visible red/green line
R2_MERGENOTPEN | Invisible blue line
R2_MERGEPEN | Visible white line
R2_MERGEPENNOT | Visible white line
R2_NOP | Invisible blue line
R2_NOT | Visible red/green line
R2_NOTCOPYPEN | Visible black line
R2_NOTMASKPEN | Visible red/green line
R2_NOTMERGEPEN | Visible black line
R2_NOTXORPEN | Invisible blue line
R2_WHITE | Visible white line
R2_XORPEN | Visible red/green line


Ternary Raster Operations

This section lists the ternary raster-operation codes used by the BitBlt, PatBlt, and StretchBlt functions. Ternary raster-operation codes define how GDI combines the bits in a source bitmap with the bits in the destination bitmap.

Each raster-operation code represents a Boolean operation in which the values of the pixels in the source, the selected brush, and the destination are combined. The following are the three operands used in these operations.

Operand | Meaning
D | Destination bitmap
P | Selected brush (also called pattern)
S | Source bitmap

Boolean operators used in these operations follow.

Operator | Meaning
a | Bitwise AND
n | Bitwise NOT (inverse)
o | Bitwise OR
x | Bitwise exclusive OR (XOR)

All Boolean operations are presented in reverse Polish notation. For example, the following operation replaces the values of the pixels in the destination bitmap with a combination of the pixel values of the source and brush:

PSo

The following operation combines the values of the pixels in the source and brush with the pixel values of the destination bitmap (there are alternative spellings of the same function, so although a particular spelling may not be in the list, an equivalent form would be):

DPSoo

Each raster-operation code is a 32-bit integer whose high-order word is a Boolean operation index and whose low-order word is the operation code. The 16-bit operation index is a zero-extended, 8-bit value that represents the result of the Boolean operation on predefined brush, source, and destination values. For example, the operation indexes for the PSo and DPSoo operations are shown in the following list.

P | S | D | PSo | DPSoo
0 | 0 | 0 | 0 | 0
0 | 0 | 1 | 0 | 1
0 | 1 | 0 | 1 | 1
0 | 1 | 1 | 1 | 1
1 | 0 | 0 | 1 | 1
1 | 0 | 1 | 1 | 1
1 | 1 | 0 | 1 | 1
1 | 1 | 1 | 1 | 1
Operation index: |  |  | 00FCh | 00FEh

In this case, PSo has the operation index 00FC (read from the bottom up); DPSoo has the operation index 00FE. These values define the location of the corresponding raster-operation codes, as shown in Table A.1, "Raster-Operation Codes." The PSo operation is in line 252 (00FCh) of the table; DPSoo is in line 254 (00FEh).

The most commonly used raster operations have been given special names in the SDK header file, WINDOWS.H. You should use these names whenever possible in your applications.

When the source and destination bitmaps are monochrome, a bit value of zero represents a black pixel and a bit value of 1 represents a white pixel. When the source and the destination bitmaps are color, those colors are represented with RGB values. For more information about RGB values, see RGB.

Raster-Operation Codes

Boolean function (hexadecimal) | Raster operation (hexadecimal) | Boolean function in reverse Polish | Common name
00 | 00000042 | 0 | BLACKNESS
01 | 00010289 | DPSoon | –
02 | 00020C89 | DPSona | –
03 | 000300AA | PSon | –
04 | 00040C88 | SDPona | –
05 | 000500A9 | DPon | –
06 | 00060865 | PDSxnon | –
07 | 000702C5 | PDSaon | –
08 | 00080F08 | SDPnaa | –
09 | 00090245 | PDSxon | –
0A | 000A0329 | DPna | –
0B | 000B0B2A | PSDnaon | –
0C | 000C0324 | SPna | –
0D | 000D0B25 | PDSnaon | –
0E | 000E08A5 | PDSonon | –
0F | 000F0001 | Pn | –
10 | 00100C85 | PDSona | –
11 | 001100A6 | DSon | NOTSRCERASE
12 | 00120868 | SDPxnon | –
13 | 001302C8 | SDPaon | –
14 | 00140869 | DPSxnon | –
15 | 001502C9 | DPSaon | –
16 | 00165CCA | PSDPSanaxx | –
17 | 00171D54 | SSPxDSxaxn | –
18 | 00180D59 | SPxPDxa | –
19 | 00191CC8 | SDPSanaxn | –
1A | 001A06C5 | PDSPaox | –
1B | 001B0768 | SDPSxaxn | –
1C | 001C06CA | PSDPaox | –
1D | 001D0766 | DSPDxaxn | –
1E | 001E01A5 | PDSox | –
1F | 001F0385 | PDSoan | –
20 | 00200F09 | DPSnaa | –
21 | 00210248 | SDPxon | –
22 | 00220326 | DSna | –
23 | 00230B24 | SPDnaon | –
24 | 00240D55 | SPxDSxa | –
25 | 00251CC5 | PDSPanaxn | –
26 | 002606C8 | SDPSaox | –
27 | 00271868 | SDPSxnox | –
28 | 00280369 | DPSxa | –
29 | 002916CA | PSDPSaoxxn | –
2A | 002A0CC9 | DPSana | –
2B | 002B1D58 | SSPxPDxaxn | –
2C | 002C0784 | SPDSoax | –
2D | 002D060A | PSDnox | –
2E | 002E064A | PSDPxox | –
2F | 002F0E2A | PSDnoan | –
30 | 0030032A | PSna | –
31 | 00310B28 | SDPnaon | –
32 | 00320688 | SDPSoox | –
33 | 00330008 | Sn | NOTSRCCOPY
34 | 003406C4 | SPDSaox | –
35 | 00351864 | SPDSxnox | –
36 | 003601A8 | SDPox | –
37 | 00370388 | SDPoan | –
38 | 0038078A | PSDPoax | –
39 | 00390604 | SPDnox | –
3A | 003A0644 | SPDSxox | –
3B | 003B0E24 | SPDnoan | –
3C | 003C004A | PSx | –
3D | 003D18A4 | SPDSonox | –
3E | 003E1B24 | SPDSnaox | –
3F | 003F00EA | PSan | –
40 | 00400F0A | PSDnaa | –
41 | 00410249 | DPSxon | –
42 | 00420D5D | SDxPDxa | –
43 | 00431CC4 | SPDSanaxn | –
44 | 00440328 | SDna | SRCERASE
45 | 00450B29 | DPSnaon | –
46 | 004606C6 | DSPDaox | –
47 | 0047076A | PSDPxaxn | –
48 | 00480368 | SDPxa | –
49 | 004916C5 | PDSPDaoxxn | –
4A | 004A0789 | DPSDoax | –
4B | 004B0605 | PDSnox | –
4C | 004C0CC8 | SDPana | –
4D | 004D1954 | SSPxDSxoxn | –
4E | 004E0645 | PDSPxox | –
4F | 004F0E25 | PDSnoan | –
50 | 00500325 | PDna | –
51 | 00510B26 | DSPnaon | –
52 | 005206C9 | DPSDaox | –
53 | 00530764 | SPDSxaxn | –
54 | 005408A9 | DPSonon | –
55 | 00550009 | Dn | DSTINVERT
56 | 005601A9 | DPSox | –
57 | 00570389 | DPSoan | –
58 | 00580785 | PDSPoax | –
59 | 00590609 | DPSnox | –
5A | 005A0049 | DPx | PATINVERT
5B | 005B18A9 | DPSDonox | –
5C | 005C0649 | DPSDxox | –
5D | 005D0E29 | DPSnoan | –
5E | 005E1B29 | DPSDnaox | –
5F | 005F00E9 | DPan | –
60 | 00600365 | PDSxa | –
61 | 006116C6 | DSPDSaoxxn | –
62 | 00620786 | DSPDoax | –
63 | 00630608 | SDPnox | –
64 | 00640788 | SDPSoax | –
65 | 00650606 | DSPnox | –
66 | 00660046 | DSx | SRCINVERT
67 | 006718A8 | SDPSonox | –
68 | 006858A6 | DSPDSonoxxn | –
69 | 00690145 | PDSxxn | –
6A | 006A01E9 | DPSax | –
6B | 006B178A | PSDPSoaxxn | –
6C | 006C01E8 | SDPax | –
6D | 006D1785 | PDSPDoaxxn | –
6E | 006E1E28 | SDPSnoax | –
6F | 006F0C65 | PDSxnan | –
70 | 00700CC5 | PDSana | –
71 | 00711D5C | SSDxPDxaxn | –
72 | 00720648 | SDPSxox | –
73 | 00730E28 | SDPnoan | –
74 | 00740646 | DSPDxox | –
75 | 00750E26 | DSPnoan | –
76 | 00761B28 | SDPSnaox | –
77 | 007700E6 | DSan | –
78 | 007801E5 | PDSax | –
79 | 00791786 | DSPDSoaxxn | –
7A | 007A1E29 | DPSDnoax | –
7B | 007B0C68 | SDPxnan | –
7C | 007C1E24 | SPDSnoax | –
7D | 007D0C69 | DPSxnan | –
7E | 007E0955 | SPxDSxo | –
7F | 007F03C9 | DPSaan | –
80 | 008003E9 | DPSaa | –
81 | 00810975 | SPxDSxon | –
82 | 00820C49 | DPSxna | –
83 | 00831E04 | SPDSnoaxn | –
84 | 00840C48 | SDPxna | –
85 | 00851E05 | PDSPnoaxn | –
86 | 008617A6 | DSPDSoaxx | –
87 | 008701C5 | PDSaxn | –
88 | 008800C6 | DSa | SRCAND
89 | 00891B08 | SDPSnaoxn | –
8A | 008A0E06 | DSPnoa | –
8B | 008B0666 | DSPDxoxn | –
8C | 008C0E08 | SDPnoa | –
8D | 008D0668 | SDPSxoxn | –
8E | 008E1D7C | SSDxPDxax | –
8F | 008F0CE5 | PDSanan | –
90 | 00900C45 | PDSxna | –
91 | 00911E08 | SDPSnoaxn | –
92 | 009217A9 | DPSDPoaxx | –
93 | 009301C4 | SPDaxn | –
94 | 009417AA | PSDPSoaxx | –
95 | 009501C9 | DPSaxn | –
96 | 00960169 | DPSxx | –
97 | 0097588A | PSDPSonoxx | –
98 | 00981888 | SDPSonoxn | –
99 | 00990066 | DSxn | –
9A | 009A0709 | DPSnax | –
9B | 009B07A8 | SDPSoaxn | –
9C | 009C0704 | SPDnax | –
9D | 009D07A6 | DSPDoaxn | –
9E | 009E16E6 | DSPDSaoxx | –
9F | 009F0345 | PDSxan | –
A0 | 00A000C9 | DPa | –
A1 | 00A11B05 | PDSPnaoxn | –
A2 | 00A20E09 | DPSnoa | –
A3 | 00A30669 | DPSDxoxn | –
A4 | 00A41885 | PDSPonoxn | –
A5 | 00A50065 | PDxn | –
A6 | 00A60706 | DSPnax | –
A7 | 00A707A5 | PDSPoaxn | –
A8 | 00A803A9 | DPSoa | –
A9 | 00A90189 | DPSoxn | –
AA | 00AA0029 | D | –
AB | 00AB0889 | DPSono | –
AC | 00AC0744 | SPDSxax | –
AD | 00AD06E9 | DPSDaoxn | –
AE | 00AE0B06 | DSPnao | –
AF | 00AF0229 | DPno | –
B0 | 00B00E05 | PDSnoa | –
B1 | 00B10665 | PDSPxoxn | –
B2 | 00B21974 | SSPxDSxox | –
B3 | 00B30CE8 | SDPanan | –
B4 | 00B4070A | PSDnax | –
B5 | 00B507A9 | DPSDoaxn | –
B6 | 00B616E9 | DPSDPaoxx | –
B7 | 00B70348 | SDPxan | –
B8 | 00B8074A | PSDPxax | –
B9 | 00B906E6 | DSPDaoxn | –
BA | 00BA0B09 | DPSnao | –
BB | 00BB0226 | DSno | MERGEPAINT
BC | 00BC1CE4 | SPDSanax | –
BD | 00BD0D7D | SDxPDxan | –
BE | 00BE0269 | DPSxo | –
BF | 00BF08C9 | DPSano | –
C0 | 00C000CA | PSa | MERGECOPY
C1 | 00C11B04 | SPDSnaoxn | –
C2 | 00C21884 | SPDSonoxn | –
C3 | 00C3006A | PSxn | –
C4 | 00C40E04 | SPDnoa | –
C5 | 00C50664 | SPDSxoxn | –
C6 | 00C60708 | SDPnax | –
C7 | 00C707AA | PSDPoaxn | –
C8 | 00C803A8 | SDPoa | –
C9 | 00C90184 | SPDoxn | –
CA | 00CA0749 | DPSDxax | –
CB | 00CB06E4 | SPDSaoxn | –
CC | 00CC0020 | S | SRCCOPY
CD | 00CD0888 | SDPono | –
CE | 00CE0B08 | SDPnao | –
CF | 00CF0224 | SPno | –
D0 | 00D00E0A | PSDnoa | –
D1 | 00D1066A | PSDPxoxn | –
D2 | 00D20705 | PDSnax | –
D3 | 00D307A4 | SPDSoaxn | –
D4 | 00D41D78 | SSPxPDxax | –
D5 | 00D50CE9 | DPSanan | –
D6 | 00D616EA | PSDPSaoxx | –
D7 | 00D70349 | DPSxan | –
D8 | 00D80745 | PDSPxax | –
D9 | 00D906E8 | SDPSaoxn | –
DA | 00DA1CE9 | DPSDanax | –
DB | 00DB0D75 | SPxDSxan | –
DC | 00DC0B04 | SPDnao | –
DD | 00DD0228 | SDno | –
DE | 00DE0268 | SDPxo | –
DF | 00DF08C8 | SDPano | –
E0 | 00E003A5 | PDSoa | –
E1 | 00E10185 | PDSoxn | –
E2 | 00E20746 | DSPDxax | –
E3 | 00E306EA | PSDPaoxn | –
E4 | 00E40748 | SDPSxax | –
E5 | 00E506E5 | PDSPaoxn | –
E6 | 00E61CE8 | SDPSanax | –
E7 | 00E70D79 | SPxPDxan | –
E8 | 00E81D74 | SSPxDSxax | –
E9 | 00E95CE6 | DSPDSanaxxn | –
EA | 00EA02E9 | DPSao | –
EB | 00EB0849 | DPSxno | –
EC | 00EC02E8 | SDPao | –
ED | 00ED0848 | SDPxno | –
EE | 00EE0086 | DSo | SRCPAINT
EF | 00EF0A08 | SDPnoo | –
F0 | 00F00021 | P | PATCOPY
F1 | 00F10885 | PDSono | –
F2 | 00F20B05 | PDSnao | –
F3 | 00F3022A | PSno | –
F4 | 00F40B0A | PSDnao | –
F5 | 00F50225 | PDno | –
F6 | 00F60265 | PDSxo | –
F7 | 00F708C5 | PDSano | –
F8 | 00F802E5 | PDSao | –
F9 | 00F90845 | PDSxno | –
FA | 00FA0089 | DPo | –
FB | 00FB0A09 | DPSnoo | PATPAINT
FC | 00FC008A | PSo | –
FD | 00FD0A0A | PSDnoo | –
FE | 00FE02A9 | DPSoo | –
FF | 00FF0062 | 1 | WHITENESS
8000 | 80000000 |  | Windows 98/Me, Windows 2000 or later: NOMIRRORBITMAP


Paths

A path is one or more figures (or shapes) that are filled, outlined, or both filled and outlined. Win32-based applications use paths in many ways. Paths are used in drawing and painting applications. Computer-aided design (CAD) applications use paths to create unique clipping regions, to draw outlines of irregular shapes, and to fill the interiors of irregular shapes. An irregular shape is a shape composed of Bézier curves and straight lines. (A regular shape is an ellipse, a circle, a rectangle, or a polygon.)

  • About Paths
  • Using Paths
  • Path Reference


About Paths

A path is one of the objects associated with a device context (DC). However, unlike the default objects (the pen, the brush, and the font) that are part of any new DC, there is no default path. For more information about DCs, see Device Contexts.

To create a path and select it into a DC, it is first necessary to define the points that describe it. This is done by calling the BeginPath function, specifying the appropriate drawing functions, and then by calling the EndPath function. This combination of functions (BeginPath, drawing functions, and EndPath) constitute a path bracket. The following table shows which drawing functions can be used on the different Windows operating systems.

Drawing function | Operating system
AngleArc | Windows NT/2000
Arc | Windows NT/2000
ArcTo | Windows NT/2000
Chord | Windows NT/2000
CloseFigure | Windows 95/98 and Windows NT/2000
Ellipse | Windows NT/2000
ExtTextOut | Windows 95/98 and Windows NT/2000
LineTo | Windows 95/98 and Windows NT/2000
MoveToEx | Windows 95/98 and Windows NT/2000
Pie | Windows NT/2000
PolyBezier | Windows 95/98 and Windows NT/2000
PolyBezierTo | Windows 95/98 and Windows NT/2000
PolyDraw | Windows NT/2000
Polygon | Windows 95/98 and Windows NT/2000
Polyline | Windows 95/98 and Windows NT/2000
PolylineTo | Windows 95/98 and Windows NT/2000
PolyPolygon | Windows 95/98 and Windows NT/2000
PolyPolyline | Windows 95/98 and Windows NT/2000
Rectangle | Windows NT/2000
RoundRect | Windows NT/2000
TextOut | Windows 95/98 and Windows NT/2000

When an application calls EndPath, the system selects the associated path into the specified DC. (If another path had previously been selected into the DC, the system deletes that path without saving it.) After the system selects the path into the DC, an application can operate on the path in one of the following ways:

  • Draw the outline of the path (using the current pen).
  • Paint the interior of the path (using the current brush).
  • Draw the outline and fill the interior of the path.
  • Modify the path (converting curves to line segments).
  • Convert the path into a clip path.
  • Convert the path into a region.
  • Flatten the path by converting each curve in the path into a series of line segments.
  • Retrieve the coordinates of the lines and curves that compose a path.


Outlined and Filled Paths

An application can draw the outline of a path by calling the StrokePath function, it can fill the interior of a path by calling the FillPath function, and it can both outline and fill the path by calling the StrokeAndFillPath function.

Whenever an application fills a path, the system uses the DC's current fill mode. An application can retrieve this mode by calling the GetPolyFillMode function, and it can set a new fill mode by calling the SetPolyFillMode function. For a description of the two fill modes, see Regions.

The following illustration shows the cross-section of an object created by a computer-aided design (CAD) application using paths that were both outlined and filled.


Transformations of Paths

Paths are defined using logical units and current transformations. (If the SetWorldTransform function has been called, the logical units are world units; otherwise, the logical units are page units.) An application can use world transformations to scale, rotate, shear, translate, and reflect the lines and Bézier curves that define a path.

Note A world transformation within a path bracket only affects those lines and curves drawn after the transformation was set. It will have no affect on those lines and curves that were drawn before it was set. For a description of the world transformation, see Coordinate Spaces and Transformations.

An application can also use SetWorldTransform to outline the shape of the pen used to outline a path if the pen is a geometric pen. For a description of geometric pens, see Pens.


Clip Paths and Graphic Effects

An application can use clipping and paths to create special graphic effects. The following illustration shows a string of text drawn with a large Arial font.

The next illustration shows the result of selecting the text as a clip path and drawing radial lines for a circle whose center is located above and left of the string.

Note Before graphics device interface (GDI) adds text created with a bitmapped font to a path, it converts the font to an outline or vector font.

An application creates a clip path by generating a path bracket and then calling the SelectClipPath function. After a clip path is selected into a DC, output only appears within the borders of the path.

In addition to creating special graphics effects, clip paths are also useful in applications that save images as enhanced metafiles. By using a clip path, an application is able to ensure device independence because the units used to specify a path are logical units.


Conversion of Paths to Regions

An application can convert a path into a region by calling the PathToRegion function. Like SelectClipPath, PathToRegion is useful in the creation of special graphics effects. For example, there are no functions that allow an application to offset a path; however, there is a function that enables an application to offset a region (OffsetRgn). Using PathToRegion, an application can create the effect of animating a complex shape by creating a path that defines the shape, converting the path into a region (by calling PathToRegion), and then repeatedly painting, moving, and erasing the region (by calling functions in a sequence, such as FillRgn, OffsetRgn, and FillRgn).


Curved Paths

An application can flatten the curves in a path by calling the FlattenPath function. This function is especially useful for applications that fit text onto the contour of a path which contains curves. To fit the text, the application must perform the following steps:

  1. Create the path where the text appears.
  2. Call the FlattenPath function to convert the curves in a path into line segments.
  3. Call the GetPath function to retrieve those line segments.
  4. Calculate the length of each line and the width of each character in the string.
  5. Use line-width and character-width data to position each character along the curve.


Using Paths

This section contains a code sample that enables the user to select a font of a particular point size (by using the Choose Font dialog box), select a clip path (by using text drawn with this font), and then view the result of clipping to the text.

This code sample was used to create the illustration that appears in Clip Paths.

CHOOSEFONT cf;          // common dialog box font structure
LOGFONT lf;             // logical font structure
HFONT hfont;            // new logical font handle
HFONT hfontOld;         // original logical font handle
HDC hdc;                // display DC handle
int nXStart, nYStart;   // drawing coordinates
RECT rc;                // structure for painting window
SIZE sz;                // structure that receives text extents
double aflSin[90];      // sine of 0-90 degrees
double aflCos[90];      // cosine of 0-90 degrees
double flRadius,a;      // radius of circle
int iMode;              // clipping mode
HRGN hrgn;              // clip region handle

LRESULT APIENTRY MainWndProc(
    HWND hwnd,                // window handle
    UINT message,             // type of message
    WPARAM wParam,            // additional information
    LPARAM lParam)            // additional information

{

    PAINTSTRUCT ps;

    switch (message)
    {
        case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
            EndPaint(hwnd, &ps);
            break;

        case WM_COMMAND:     // command from app's menu
            switch (wParam)
            {
                case IDM_VANISH:  // erases client area
                    hdc = GetDC(hwnd);
                    GetClientRect(hwnd, &rc);
                    FillRect(hdc, &rc, GetStockObject(WHITE_BRUSH));
                    ReleaseDC(hwnd, hdc);
                    break;

                case IDM_AND: // sets clip mode to RGN_AND
                    iMode = RGN_AND;
                    break;

                case IDM_COPY: // sets clip mode to RGN_COPY
                    iMode = RGN_COPY;
                    break;

                case IDM_DIFF: // sets clip mode to RGN_DIFF
                    iMode = RGN_DIFF;
                    break;

                case IDM_OR: // sets clip mode to RGN_OR
                    iMode = RGN_OR;
                    break;

                case IDM_XOR: // sets clip mode to RGN_XOR
                    iMode = RGN_XOR;
                    break;

                case IDM_CLIP_PATH:

                    // Retrieve a cached DC for the window.

                    hdc = GetDC(hwnd);

                    // Use the font requested by the user in the
                    // Choose Font dialog box to create a logical
                    // font, then select that font into the DC.

                    hfont = CreateFontIndirect(cf.lpLogFont);
                    hfontOld = SelectObject(hdc, hfont);

                    // Retrieve the dimensions of the rectangle
                    // that surrounds the text.

                    GetTextExtentPoint32(hdc, "Clip Path", 9, &sz);

                    // Set a clipping region using the rect that
                    // surrounds the text.

                    hrgn = CreateRectRgn(nXStart, nYStart,
                        nXStart + sz.cx,
                        nYStart + sz.cy);

                    SelectClipRgn(hdc, hrgn);

                    // Create a clip path using text drawn with
                    // the user's requested font.

                    BeginPath(hdc);
                    TextOut(hdc, nXStart, nYStart, "Clip Path", 9);
                    EndPath(hdc);
                    SelectClipPath(hdc, iMode);

                    // Compute the sine of 0, 1, ... 90 degrees.
                    for (i = 0; i < 90; i++)
                    {
                        aflSin[i] = sin( (((double)i) / 180.0)
                                    * 3.14159);
                    }

                    // Compute the cosine of 0, 1,... 90 degrees.
                    for (i = 0; i < 90; i++)
                    {
                        aflCos[i] = cos( (((double)i) / 180.0)
                                    * 3.14159);
                    }

                    // Set the radius value.

                    flRadius = (double)(2 * sz.cx);

                    // Draw the 90 rays extending from the
                    // radius to the edge of the circle.

                    for (i = 0; i < 90; i++)
                    {
                        MoveToEx(hdc, nXStart, nYStart,
                           (LPPOINT) NULL);
                        LineTo(hdc, nXStart + ((int) (flRadius
                            * aflCos[i])),
                               nYStart + ((int) (flRadius
                            * aflSin[i])));
                    }

                    // Reselect the original font into the DC.

                    SelectObject(hdc, hfontOld);

                    // Delete the user's font.

                    DeleteObject(hfont);

                    // Release the DC.

                    ReleaseDC(hwnd, hdc);

                    break;

                case IDM_FONT:

                    // Initialize necessary members.

                    cf.lStructSize = sizeof (CHOOSEFONT);
                    cf.hwndOwner = hwnd;
                    cf.lpLogFont = &lf;
                    cf.Flags = CF_SCREENFONTS | CF_EFFECTS;
                    cf.rgbColors = RGB(0, 255, 255);
                    cf.nFontType = SCREEN_FONTTYPE;

                    // Display the Font dialog box, allow the user
                    // to choose a font, and render text in the
                    // window with that selection.

                    if (ChooseFont(&cf))
                    {
                        hdc = GetDC(hwnd);
                        hfont = CreateFontIndirect(cf.lpLogFont);
                        hfontOld = SelectObject(hdc, hfont);
                        crOld = SetTextColor(hdc, cf.rgbColors);
                        TextOut(hdc, nXStart, nYStart,
                            "Clip Path", 9);
                        SetTextColor(hdc, crOld);
                        SelectObject(hdc, hfontOld);
                        DeleteObject(hfont);
                        ReleaseDC(hwnd, hdc);
                    }

                    break;

                default:
                    return DefWindowProc(hwnd, message, wParam,
                        lParam);
            }
            break;

        case WM_DESTROY:    // window is being destroyed
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}


Path Reference

The following elements are used to create, alter, or draw paths.

  • Path Functions


Path Functions

The following functions are used to create, alter, or draw paths.

Function | Description
AbortPath | Closes and discards any paths in the specified device context.
BeginPath | Opens a path bracket in the specified device context.
CloseFigure | Closes an open figure in a path.
EndPath | Closes a path bracket and selects the path defined by the bracket into the specified device context.
FillPath | Closes any open figures in the current path and fills the path's interior by using the current brush and polygon-filling mode.
FlattenPath | Transforms any curves in the path that is selected into the current device context (DC), turning each curve into a sequence of lines.
GetMiterLimit | Retrieves the miter limit for the specified device context.
GetPath | Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the specified device context.
PathToRegion | Creates a region from the path that is selected into the specified device context.
SetMiterLimit | Sets the limit for the length of miter joins for the specified device context.
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.
StrokePath | Renders the specified path by using the current pen.
WidenPath | Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context.


AbortPath

The AbortPath function closes and discards any paths in the specified device context.

BOOL AbortPath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context from which a path will be discarded.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

If there is an open path bracket in the given 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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, EndPath


BeginPath

The BeginPath function opens a path bracket in the specified device context.

BOOL BeginPath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

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

When an application calls BeginPath for a device context, any previous paths are discarded from that device context. The following table shows which drawing functions can be used on the different Windows operating systems.

Drawing function | Operating system
AngleArc | Windows NT/2000
Arc | Windows NT/2000
ArcTo | Windows NT/2000
Chord | Windows NT/2000
CloseFigure | Windows 95/98 and Windows NT/2000
Ellipse | Windows NT/2000
ExtTextOut | Windows 95/98 and Windows NT/2000
LineTo | Windows 95/98 and Windows NT/2000
MoveToEx | Windows 95/98 and Windows NT/2000
Pie | Windows NT/2000
PolyBezier | Windows 95/98 and Windows NT/2000
PolyBezierTo | Windows 95/98 and Windows NT/2000
PolyDraw | Windows NT/2000
Polygon | Windows 95/98 and Windows NT/2000
Polyline | Windows 95/98 and Windows NT/2000
PolylineTo | Windows 95/98 and Windows NT/2000
PolyPolygon | Windows 95/98 and Windows NT/2000
PolyPolyline | Windows 95/98 and Windows NT/2000
Rectangle | Windows NT/2000
RoundRect | Windows NT/2000
TextOut | Windows 95/98 and Windows NT/2000

For an example, see Using Paths.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, EndPath, FillPath, PathToRegion, SelectClipPath, StrokeAndFillPath, StrokePath, WidenPath


CloseFigure

The CloseFigure function closes an open figure in a path.

BOOL CloseFigure(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context in which the figure will be closed.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The CloseFigure 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 MoveToEx function) and then connects the lines by using the line join style. If a figure is closed by using the LineTo function instead of CloseFigure, end caps are used to create the corner instead of a join.

The CloseFigure function should only be called if there is an open path bracket in the specified 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.)

After a call to CloseFigure, adding a line or curve to the path starts a new figure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, EndPath, ExtCreatePen, LineTo, MoveToEx


EndPath

The EndPath function closes a path bracket and selects the path defined by the bracket into the specified device context.

BOOL EndPath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context into which the new path is selected.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER

For an example, see Using Paths.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath


FillPath

The FillPath function 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(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to a device context that contains a valid path.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

After its interior is filled, the path is discarded from the DC identified by the hdc parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, SetPolyFillMode, StrokeAndFillPath, StrokePath


FlattenPath

The FlattenPath function transforms any curves in the path that is selected into the current device context (DC), turning each curve into a sequence of lines.

BOOL FlattenPath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to a DC that contains a valid path.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, WidenPath


GetMiterLimit

The GetMiterLimit function retrieves the miter limit for the specified device context.

BOOL GetMiterLimit(
  HDC hdc,         // handle to DC
  PFLOAT peLimit   // miter limit
);

Parameters

hdc
[in] Handle to the device context.
peLimit
[out] Pointer to a floating-point value that receives the current miter limit.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, ExtCreatePen, SetMiterLimit


GetPath

The GetPath function retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the specified device context.

int GetPath(
  HDC hdc,           // handle to DC
  LPPOINT lpPoints,  // path vertices
  LPBYTE lpTypes,    // array of path vertex types
  int nSize          // count of points defining path
);

Parameters

hdc
[in] Handle to a device context that contains a closed path.
lpPoints
[out] Pointer to an array of POINT structures that receives the line endpoints and curve control points.
lpTypes
[out] Pointer to an array of bytes that receives the vertex types. This parameter can be one of the following values.
Type | Description
PT_MOVETO | Specifies that the corresponding point in the lpPoints parameter 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 Bézier curve.
PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bézier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point.

A PT_LINETO or PT_BEZIERTO value may be combined with the following value (by using the bitwise operator OR) to indicate that the corresponding point is the last point in a figure and the figure should be closed.
Flag | Description
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.

nSize
[in] Specifies the total number of POINT structures that can be stored in the array pointed to by lpPoints. This value must be the same as the number of bytes that can be placed in the array pointed to by lpTypes.

Return Values

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

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_BUFFER_OVERFLOW

Remarks

The device context identified by the hdc parameter 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 function may be called before GetPath to convert all curves in the path into line segments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, FlattenPath, POINT, PolyDraw, WidenPath


PathToRegion

The PathToRegion function creates a region from the path that is selected into the specified device context. The resulting region uses device coordinates.

HRGN PathToRegion(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to a device context that contains a closed path.

Return Values

If the function succeeds, the return value identifies a valid region.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

After PathToRegion converts a path into a region, the system discards the closed path from the specified device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, EndPath, SetPolyFillMode


SetMiterLimit

The SetMiterLimit function sets the limit for the length of miter joins for the specified device context.

BOOL SetMiterLimit(
  HDC hdc,            // handle to DC
  FLOAT eNewLimit,    // new miter limit
  PFLOAT peOldLimit   // previous miter limit
);

Parameters

hdc
[in] Handle to the device context.
eNewLimit
[in] Specifies the new miter limit for the device context.
peOldLimit
[out] Pointer to a floating-point value that receives the previous miter limit. If this parameter is NULL, the previous miter limit is not returned.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, ExtCreatePen, GetMiterLimit


StrokeAndFillPath

The StrokeAndFillPath function 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(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

The StrokeAndFillPath 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.

For an example, see Drawing a Pie Chart.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, FillPath, SetPolyFillMode, StrokePath


StrokePath

The StrokePath function renders the specified path by using the current pen.

BOOL StrokePath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to a device context that contains a closed path.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The device context identified by the hdc parameter must contain a closed path.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, EndPath, ExtCreatePen


WidenPath

The WidenPath function redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context.

BOOL WidenPath(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to a device context that contains a closed path.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError. GetLastError may return one of the following error codes:

ERROR_CAN_NOT_COMPLETE
ERROR_INVALID_PARAMETER
ERROR_NOT_ENOUGH_MEMORY

Remarks

The WidenPath function is successful only if the current pen is a geometric pen created by the ExtCreatePen function, or if the pen is created with the CreatePen function and has a width, in device units, of more than one.

The device context identified by the hdc parameter must contain a closed path.

Any Bézier curves in the path are converted to sequences of straight lines approximating the widened curves. As such, no Bézier curves remain in the path after WidenPath is called.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Paths Overview, Path Functions, BeginPath, CreatePen, EndPath, ExtCreatePen, SetMiterLimit


Pens

A pen is a graphics tool that a Win32®-based application uses to draw lines and curves. Drawing applications use pens to draw freehand lines, straight lines, and curves. Computer-aided design (CAD) applications use pens to draw visible lines, hidden lines, section lines, center lines, and so on. Word processing and desktop publishing applications use pens to draw borders and rules. Spreadsheet applications use pens to designate trends in graphs and to outline bar graphs and pie charts.

  • About Pens
  • Using Pens
  • Pen Reference


About Pens

There are two types of pen: cosmetic and geometric. A cosmetic pen is used with applications requiring lines of fixed width and lines that are quickly drawn. A CAD application, for example, uses a cosmetic pen to generate hidden, section, center, and dimension lines that are between .015 and .022 inches wide — regardless of the scale factor. A geometric pen is used with applications requiring scalable lines, lines with unique end or join styles, and lines that are wider than a single pixel. A spreadsheet application, for example, uses a geometric pen to define each of the bars in a bar graph as a wide line.

  • Cosmetic Pens
  • Geometric Pens


Cosmetic Pens

The dimensions of a cosmetic pen are specified in device units. Therefore, lines drawn with a cosmetic pen always have a fixed width. Lines drawn with a cosmetic pen are generally drawn 3 to 10 times faster than lines drawn with a geometric pen. Cosmetic pens have three attributes: width, style, and color. For more information about these attributes, see Pen Attributes.

To create a cosmetic pen, use the CreatePen, CreatePenIndirect, or ExtCreatePen function. To retrieve one of the three stock cosmetic pens managed by the system, use the GetStockObject function.

After you create a pen (or obtain a handle to one of the stock pens), select the pen into the application's device context (DC) using the SelectObject function. From this point on, the application uses this pen for any line-drawing operations in its client area.


Geometric Pens

The dimensions of a geometric pen are specified in logical units. Therefore, lines drawn with a geometric pen can be scaled — that is, they may appear wider or narrower, depending on the current world transformation. For more information about world transformation, see Coordinate Spaces and Transformations.

In addition to the three attributes shared with cosmetic pens (width, style, and color), geometric pens possess the following four attributes: pattern, optional hatch, end style, and join style. For more information about these attributes, see Pen Attributes.

To create a geometric pen, an application uses the ExtCreatePen function. As with cosmetic pens, the SelectObject function selects a geometric pen into the application's DC.


Pen Attributes

There are seven pen attributes that define the type of pen and its characteristics: width, style, color, pattern, hatch, end style, and join style. Both cosmetic and geometric pens have the width, style, and color attributes. Only geometric pens have the pattern, hatch, end style, and join style attributes. The pattern and optional hatch attribute are usually associated with a brush but can also be used with geometric pens.

For more information, see the following topics:

  • Pen Width
  • Pen Style
  • Pen Color
  • Pen Pattern
  • Pen Hatch
  • Pen End Cap
  • Pen Join


Pen Width

The width attribute specifies a cosmetic pen width in device units. When used with a geometric pen, however, it specifies the pen's width in logical units. For more information about device units, see Coordinate Spaces and Transformations.

Currently, the system limits the width of cosmetic pens to a single pixel; however, future versions may remove this limitation.


Pen Style

The style attribute specifies the line pattern that appears when a particular cosmetic or geometric pen is used. There are eight predefined pen styles. The following illustration shows the seven of these styles that are defined by the system.

The inside-frame style is identical to the solid style for cosmetic pens. However, it operates differently when used with a geometric pen. If the geometric pen is wider than a single pixel and a drawing function uses the pen to draw a border around a filled object, the system draws the border inside the object's frame. By using the inside-frame style, an application can ensure that an object appears entirely within the specified dimensions, regardless of the geometric pen width.

In addition to the seven styles defined by the system, there is an eighth style that is user (or application) defined. A user-defined style generates lines with a customized series of dashes and dots.

Use the CreatePen, CreatePenIndirect, or ExtCreatePen function to create a pen that has the system-defined styles. Use the ExtCreatePen function to create a pen that has a user-defined style.


Pen Color

The color attribute specifies the pen's color. An application can create a cosmetic pen with a unique color by using the RGB macro to store the red, green, blue triplet that specifies the desired color in a COLORREF structure and passing this structure's address to the CreatePen, CreatePenIndirect, or ExtCreatePen function. (The stock pens are limited to black, white, and invisible.) For more information about RGB triplets and color, see Colors.


Pen Pattern

The pattern attribute specifies the pattern of a geometric pen.

The following illustration shows lines drawn with different geometric pens. Each pen was created using a different pattern attribute.

The first line in the previous illustration is drawn using one of the six available hatch patterns; for more information about hatch patterns, see Pen Hatch. The next line is drawn using the hollow pattern, identical to the null pattern. The third line is drawn using a custom pattern created from an 8-by-8-pixel bitmap. (For more information about bitmaps and their creation, see Bitmaps.) The last line is drawn using a solid pattern. Creating a brush and passing its handle to the ExtCreatePen function creates a pattern.


Pen Hatch

The hatch attribute specifies the hatch type of a geometric pen with the hatch pattern attribute. There are six patterns available. The following illustration shows lines drawn using different hatch patterns.


Pen End Cap

The end cap attribute specifies the shape of a geometric pen: round, square, or flat. The following illustration shows parallel lines drawn using each type of end cap.

The round and square end caps extend past the starting and ending points of a line drawn with a geometric pen; the flat end cap does not.


Pen Join

The join attribute specifies how the ends of two geometric lines are joined: beveled, mitered, or round. The following illustration shows pairs of connected lines drawn using each type of join.


ICM-Enabled Pen Functions

Microsoft® Windows® 98 and Microsoft® Windows® 2000 have been designed to work with Microsoft® Image Color Management (ICM). ICM technology ensures that a color image, graphic, or text object is rendered as close as possible to its original intent on any device, despite differences in imaging technologies and color capabilities among devices. Whether you are scanning an image or other graphic on a color scanner, downloading it over the Internet, viewing or editing it on the screen, or outputting it to paper, film, or other media, ICM version 2.0 helps you keep its colors consistent and accurate. For more information about ICM, see About Image Color Management Version 2.0

There are various functions in the graphics device interface (GDI) that use or operate on color data. The following pen functions are enabled for use with ICM:

  • CreatePen
  • ExtCreatePen


Using Pens

This section contains sample code that demonstrates the appearance of lines drawn using various pen styles and attributes.

LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam,
                             LPARAM lParam)
{
    PAINTSTRUCT ps;
    LOGBRUSH lb;
    RECT rc;
    HDC hdc;
    int i;
    HPEN hPen, hPenOld;
    DWORD dwPenStyle[] = {
                           PS_DASH,
                           PS_DASHDOT,
                           PS_DOT,
                           PS_INSIDEFRAME,
                           PS_NULL,
                           PS_SOLID
                        };
    UINT uHatch[] = {
                      HS_BDIAGONAL,
                      HS_CROSS,
                      HS_DIAGCROSS,
                      HS_FDIAGONAL,
                      HS_HORIZONTAL,
                      HS_VERTICAL
                     };

    switch (uMsg)
    {
        case WM_PAINT:
        {
            GetClientRect(hWnd, &rc);
            rc.left += 10;
            rc.top += 10;
            rc.bottom -= 10;

            // Initialize the pen's brush.
            lb.lbStyle = BS_SOLID;
            lb.lbColor = RGB(255,0,0);
            lb.lbHatch = 0;

            hdc = BeginPaint(hWnd, &ps);
            for (i = 0; i < 6; i++)
            {
                hPen = ExtCreatePen(PS_COSMETIC | dwPenStyle[i],
                                    1, &lb, 0, NULL);
                hPenOld = SelectObject(hdc, hPen);
                MoveToEx(hdc, rc.left + (i * 20), rc.top, NULL);
                LineTo(hdc, rc.left + (i * 20), rc.bottom);
                SelectObject(hdc, hPenOld);
                DeleteObject(hPen);
            }
            rc.left += 150;
            for (i = 0; i < 6; i++)
            {
                lb.lbStyle = BS_HATCHED;
                lb.lbColor = RGB(0,0,255);
                lb.lbHatch = uHatch[i];
                hPen = ExtCreatePen(PS_GEOMETRIC,
                                    5, &lb, 0, NULL);
                hPenOld = SelectObject(hdc, hPen);
                MoveToEx(hdc, rc.left + (i * 20), rc.top, NULL);
                LineTo(hdc, rc.left + (i * 20), rc.bottom);
                SelectObject(hdc, hPenOld);
                DeleteObject(hPen);
            }
            EndPaint(hWnd, &ps);

        }
        break;

        case WM_DESTROY:
            DeleteObject(hPen);
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }

    return FALSE;
}


Pen Reference

The following elements are used with pens:

  • Pen Functions
  • Pen Structures


Pen Functions

The following functions are used with pens.

Function | Description
CreatePen | Creates a logical pen that has the specified style, width, and color.
CreatePenIndirect | Creates a logical cosmetic pen that has the style, width, and color specified in a structure.
ExtCreatePen | Creates a logical cosmetic or geometric pen that has the specified style, width, and brush attributes.


CreatePen

The CreatePen function creates a logical pen that has the specified style, width, and color. The pen can subsequently be selected into a device context and used to draw lines and curves.

HPEN CreatePen(
  int fnPenStyle,    // pen style
  int nWidth,        // pen width
  COLORREF crColor   // pen color
);

Parameters

fnPenStyle
[in] Specifies the pen style. It can be any one of the following values.
Value | Meaning
PS_SOLID | The pen is solid.
PS_DASH | The pen is dashed. This style is valid only when the pen width is one or less in device units.
PS_DOT | The pen is dotted. This style is valid only when the pen width is one or less in device units.
PS_DASHDOT | The pen has alternating dashes and dots. This style is valid only when the pen width is one or less in device units.
PS_DASHDOTDOT | The pen has alternating dashes and double dots. This style is valid only when the pen width is one or less in device units.
PS_NULL | The pen is invisible.
PS_INSIDEFRAME | The pen is solid. When this pen is used in any GDI drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.

nWidth
[in] Specifies the width of the pen, in logical units. If nWidth is zero, the pen is a single pixel wide, regardless of the current transformation.

CreatePen returns a pen with the specified width bit with the PS_SOLID style if you specify a width greater than one for the following styles: PS_DASH, PS_DOT, PS_DASHDOT, PS_DASHDOTDOT.

crColor
[in] Specifies a color reference for the pen color. To generate a COLORREF structure, use the RGB macro.

Return Values

If the function succeeds, the return value is a handle that identifies a logical pen.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

If the value specified by the nWidth parameter is zero, a line drawn with the created pen always is a single pixel wide regardless of the current transformation.

If the value specified by nWidth is greater than 1, the fnPenStyle parameter must be PS_NULL, PS_SOLID, or PS_INSIDEFRAME.

If the value specified by nWidth is greater than 1 and fnPenStyle is PS_INSIDEFRAME, the line associated with the pen is drawn inside the frame of all primitives except polygons and polylines.

If the value specified by nWidth is greater than 1, fnPenStyle is PS_INSIDEFRAME, and the color specified by the crColor parameter does not match one of the entries in the logical palette, the system draws lines by using a dithered color. Dithered colors are not available with solid pens.

When you no longer need the pen, call the DeleteObject function to delete it.

ICM: No color management is done at creation. However, color management is performed when the pen is selected into an ICM-enabled device context.

For an example, see Creating Colored Pens and Brushes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Pens Overview, Pen Functions, CreatePenIndirect, COLORREF, DeleteObject, ExtCreatePen, GetObject, RGB, SelectObject


CreatePenIndirect

The CreatePenIndirect function creates a logical cosmetic pen that has the style, width, and color specified in a structure.

HPEN CreatePenIndirect(
  CONST LOGPEN *lplgpn   // style, width, and color
);

Parameters

lplgpn
[in] Pointer to a LOGPEN structure that specifies the pen's style, width, and color.

Return Values

If the function succeeds, the return value is a handle that identifies a logical cosmetic pen.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

When you no longer need the pen, call the DeleteObject function to delete it.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Pens Overview, Pen Functions, CreatePen, DeleteObject, ExtCreatePen, GetObject, LOGPEN, RGB, SelectObject


ExtCreatePen

The ExtCreatePen function creates a logical cosmetic or geometric pen that has the specified style, width, and brush attributes.

HPEN ExtCreatePen(
  DWORD dwPenStyle,      // pen style
  DWORD dwWidth,         // pen width
  CONST LOGBRUSH *lplb,  // brush attributes
  DWORD dwStyleCount,    // length of custom style array
  CONST DWORD *lpStyle   // custom style array
);

Parameters

dwPenStyle
[in] Specifies a combination of type, style, end cap, and join attributes. The values from each category are combined by using the bitwise OR operator (|).

The pen type can be one of the following values.
Value | Meaning
PS_GEOMETRIC | The pen is geometric.
PS_COSMETIC | The pen is cosmetic.

The pen style can be one of the following values.
Value | Meaning
PS_ALTERNATE | Windows NT/2000: The pen sets every other pixel. (This style is applicable only for cosmetic pens.)
PS_SOLID | The pen is solid.
PS_DASH The pen is dashed.

Windows 95: This style is not supported for geometric lines.

Windows 98: Not supported.
PS_DOT The pen is dotted.

Windows 95/98: This style is not supported for geometric lines.
PS_DASHDOT The pen has alternating dashes and dots.

Windows 95: This style is not supported for geometric lines.

Windows 98: Not supported.
PS_DASHDOTDOT The pen has alternating dashes and double dots.

Windows 95: This style is not supported for geometric lines.

Windows 98: Not supported.
PS_NULL | The pen is invisible.
PS_USERSTYLE | Windows NT/2000: The pen uses a styling array supplied by the user.
PS_INSIDEFRAME | The pen is solid. When this pen is used in any GDI drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.

The end cap is only specified for geometric pens. The end cap can be one of the following values.
Value | Meaning
PS_ENDCAP_ROUND | End caps are round.
PS_ENDCAP_SQUARE | End caps are square.
PS_ENDCAP_FLAT | End caps are flat.

The join is only specified for geometric pens. The join can be one of the following values.
Value | Meaning
PS_JOIN_BEVEL | Joins are beveled.
PS_JOIN_MITER | Joins are mitered when they are within the current limit set by the SetMiterLimit function. If it exceeds this limit, the join is beveled.
PS_JOIN_ROUND | Joins are round.

Windows 95/98: The PS_ENDCAP_ROUND, PS_ENDCAP_SQUARE, PS_ENDCAP_FLAT, PS_JOIN_BEVEL, PS_JOIN_MITER, and PS_JOIN_ROUND styles are supported only for geometric pens when used to draw paths.

dwWidth
[in] Specifies the width of the pen. If the dwPenStyle parameter is PS_GEOMETRIC, the width is given in logical units. If dwPenStyle is PS_COSMETIC, the width must be set to 1.
lplb
[in] Pointer to a LOGBRUSH structure. If dwPenStyle is PS_COSMETIC, the lbColor member specifies the color of the pen and the lbStyle member must be set to BS_SOLID. If dwPenStyle is PS_GEOMETRIC, all members must be used to specify the brush attributes of the pen.
dwStyleCount
[in] Specifies the length, in DWORD units, of the lpStyle array. This value must be zero if dwPenStyle is not PS_USERSTYLE.
lpStyle
[in] Pointer to an array. The first value specifies the length of the first dash in a user-defined style, the second value specifies the length of the first space, and so on. This pointer must be NULL if dwPenStyle is not PS_USERSTYLE.

Return Values

If the function succeeds, the return value is a handle that identifies a logical pen.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

A geometric pen can have any width and can have any of the attributes of a brush, such as dithers and patterns. A cosmetic pen can only be a single pixel wide and must be a solid color, but cosmetic pens are generally faster than geometric pens.

The width of a geometric pen is always specified in world units. The width of a cosmetic pen is always 1.

End caps and joins are only specified for geometric pens.

After an application creates a logical pen, it can select that pen into a device context by calling the SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

If dwPenStyle is PS_COSMETIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in style units. A style unit is defined by the device where the pen is used to draw a line.

If dwPenStyle is PS_GEOMETRIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in logical units.

If dwPenStyle is PS_ALTERNATE, the style unit is ignored and every other pixel is set.

If the lbStyle member of the LOGBRUSH structure pointed to by lplb is BS_PATTERN, the bitmap pointed to by the lbHatch member of that structure cannot be a DIB section. A DIB section is a bitmap created by CreateDIBSection. If that bitmap is a DIB section, the ExtCreatePen function fails.

When an application no longer requires a specified pen, it should call the DeleteObject function to delete the pen.

ICM: No color management is done at pen creation. However, color management is performed when the pen is selected into an ICM-enabled device context.

For an example, see Using Pens.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Pens Overview, Pen Functions, CreateDIBSection, CreatePen, CreatePenIndirect, DeleteObject, GetObject, LOGBRUSH, SelectObject, SetMiterLimit


Pen Structures

The following structures are used with pens.

EXTLOGPEN
LOGPEN


EXTLOGPEN

The EXTLOGPEN structure defines the pen style, width, and brush attributes for an extended pen. This structure is used by the GetObject function when it retrieves a description of a pen that was created when an application called the ExtCreatePen function.

typedef struct tagEXTLOGPEN {
    DWORD     elpPenStyle;
    DWORD     elpWidth;
    UINT      elpBrushStyle;
    COLORREF  elpColor;
    ULONG_PTR elpHatch;
    DWORD     elpNumEntries;
    DWORD     elpStyleEntry[1];
} EXTLOGPEN, *PEXTLOGPEN;

Members

elpPenStyle
Specifies a combination of pen type, style, end cap style, and join style. The values from each category can be retrieved by using a bitwise AND operator with the appropriate mask.

The elpPenStyle member masked with PS_TYPE_MASK has one of the following pen type values.
Value | Meaning
PS_GEOMETRIC | The pen is geometric.
PS_COSMETIC | The pen is cosmetic.

The elpPenStyle member masked with PS_STYLE_MASK has one of the following pen styles values:
Value | Meaning
PS_DASH | The pen is dashed.
PS_DASHDOT | The pen has alternating dashes and dots.
PS_DASHDOTDOT | The pen has alternating dashes and double dots.
PS_DOT | The pen is dotted.
PS_INSIDEFRAME | The pen is solid. When this pen is used in any GDI drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to PS_GEOMETRIC pens.
PS_NULL | The pen is invisible.
PS_SOLID | The pen is solid.
PS_USERSTYLE | The pen uses a styling array supplied by the user.

The following category applies only to PS_GEOMETRIC pens. The elpPenStyle member masked with PS_ENDCAP_MASK has one of the following end cap values.
Value | Meaning
PS_ENDCAP_FLAT | Line end caps are flat.
PS_ENDCAP_ROUND | Line end caps are round.
PS_ENDCAP_SQUARE | Line end caps are square.

The following category applies only to PS_GEOMETRIC pens. The elpPenStyle member masked with PS_JOIN_MASK has one of the following join values.
Value | Meaning
PS_JOIN_BEVEL | Line joins are beveled.
PS_JOIN_MITER | Line joins are mitered when they are within the current limit set by the SetMiterLimit function. A join is beveled when it would exceed the limit.
PS_JOIN_ROUND | Line joins are round.

elpWidth
Specifies the width of the pen. If the elpPenStyle member is PS_GEOMETRIC, this value is the width of the line in logical units. Otherwise, the lines are cosmetic and this value is 1, which indicates a line with a width of one pixel.
elpBrushStyle
Specifies the brush style of the pen. The elpBrushStyle member value can be one of the following.
Value | Meaning
BS_DIBPATTERN | Specifies a pattern brush defined by a DIB specification. If elpBrushStyle is BS_DIBPATTERN, the elpHatch member contains a handle to a packed DIB. For more information, see discussion in elpHatch
BS_DIBPATTERNPT | Specifies a pattern brush defined by a DIB specification. If elpBrushStyle is BS_DIBPATTERNPT, the elpHatch member contains a pointer to a packed DIB. For more information, see discussion in elpHatch.
BS_HATCHED | Specifies a hatched brush.
BS_HOLLOW | Specifies a hollow or NULL brush.
BS_PATTERN | Specifies a pattern brush defined by a memory bitmap.
BS_SOLID | Specifies a solid brush.

elpColor
If elpBrushStyle is BS_SOLID or BS_HATCHED, elpColor specifies the color in which the pen is to be drawn. For BS_HATCHED, the SetBkMode and SetBkColor functions determine the background color.

If elpBrushStyle is BS_HOLLOW or BS_PATTERN, elpColor is ignored.

If elpBrushStyle is BS_DIBPATTERN or BS_DIBPATTERNPT, the low-order word of elpColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit RGB values or indices into the currently realized logical palette. The elpColor value must be one of the following.
Value | Meaning
DIB_PAL_COLORS | The color table consists of an array of 16-bit indices into the currently realized logical palette.
DIB_RGB_COLORS | The color table contains literal RGB values.

The RGB macro is used to generate a COLORREF structure.

elpHatch
If elpBrushStyle is BS_PATTERN, elpHatch is a handle to the bitmap that defines the pattern.

If elpBrushStyle is BS_SOLID or BS_HOLLOW, elpHatch is ignored.

If elpBrushStyle is BS_DIBPATTERN, the elpHatch member is a handle to a packed DIB. To obtain this handle, an application calls the GlobalAlloc function with GMEM_MOVEABLE (or LocalAlloc with LMEM_MOVEABLE) to allocate a block of memory and then fills the memory with the packed DIB. A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If elpBrushStyle is BS_DIBPATTERNPT, the elpHatch member is a pointer to a packed DIB. The pointer derives from the memory block created by LocalAlloc with LMEM_FIXED set or by GlobalAlloc with GMEM_FIXED set, or it is the pointer returned by a call like LocalLock (handle_to_the_dib). A packed DIB consists of a BITMAPINFO structure immediately followed by the array of bytes that define the pixels of the bitmap.

If elpBrushStyle is BS_HATCHED, the elpHatch member specifies the orientation of the lines used to create the hatch. It can be one of the following values.
Value | Meaning
HS_BDIAGONAL | 45-degree upward hatch (left to right)
HS_CROSS | Horizontal and vertical crosshatch
HS_DIAGCROSS | 45-degree crosshatch
HS_FDIAGONAL | 45-degree downward hatch (left to right)
HS_HORIZONTAL | Horizontal hatch
HS_VERTICAL | Vertical hatch

elpNumEntries
Specifies the number of entries in the style array in the elpStyleEntry member. This value is zero if elpPenStyle does not specify PS_USERSTYLE.
elpStyleEntry
Specifies a user-supplied style array. The array is specified with a finite length, but it is used as if it repeated indefinitely. The first entry in the array specifies the length of the first dash. The second entry specifies the length of the first gap. Thereafter, lengths of dashes and gaps alternate.

If elpWidth specifies geometric lines, the lengths are in logical units. Otherwise, the lines are cosmetic and lengths are in device units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Pens Overview, Pen Structures, BITMAPINFO, COLORREF, ExtCreatePen, GetObject, GlobalAlloc, RGB, SetBkColor, SetBkMode


LOGPEN

The LOGPEN structure defines the style, width, and color of a pen. The CreatePenIndirect function uses the LOGPEN structure.

typedef struct tagLOGPEN {
    UINT     lopnStyle;
    POINT    lopnWidth;
    COLORREF lopnColor;
} LOGPEN, *PLOGPEN;

Members

lopnStyle
Specifies the pen style, which can be one of the following values.
Value | Meaning
PS_SOLID | The pen is solid.
PS_DASH | The pen is dashed.
PS_DOT | The pen is dotted.
PS_DASHDOT | The pen has alternating dashes and dots.
PS_DASHDOTDOT | The pen has dashes and double dots.
PS_NULL | The pen is invisible.
PS_INSIDEFRAME | The pen is solid. When this pen is used in any GDI drawing function that takes a bounding rectangle, the dimensions of the figure are shrunk so that it fits entirely in the bounding rectangle, taking into account the width of the pen. This applies only to geometric pens.

lopnWidth
Specifies the POINT structure that contains the pen width, in logical units. If the pointer member is NULL, the pen is one pixel wide on raster devices. The y member in the POINT structure for lopnWidth is not used.
lopnColor
Specifies the pen color. To generate a COLORREF structure, use the RGB macro.

Remarks

If the width of the pen is greater than 1 and the pen style is PS_INSIDEFRAME, the line is drawn inside the frame of all GDI objects except polygons and polylines. If the pen color does not match an available RGB value, the pen is drawn with a logical (dithered) color. If the pen width is less than or equal to 1, the PS_INSIDEFRAME style is identical to the PS_SOLID style.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Pens Overview, Pen Structures, COLORREF, CreatePenIndirect, POINT, RGB


Printing and Print Spooler

Microsoft® Windows® and Microsoft Windows NT®/Windows 2000 provide a complete set of functions that allow applications to print on a variety of devices: laser printers, vector plotters, raster printers, and fax machines.

  • About Printing
  • Using the Printing Functions
  • Printing and Print Spooler Reference


About Printing

One of the chief features of Microsoft® Win32® printing functions is their support of device independence. Instead of issuing device-specific commands to draw output on a particular printer or plotter, an application calls high-level functions from the graphics device interface (GDI). For example, to print a bitmapped image, an application can call the BitBlt function, supplying the coordinates for the bitmap as well as handles identifying the source and destination device contexts (DCs). The call to BitBlt is then converted to raw device commands by a printer device driver. A device driver is a dynamic-link library (DLL) that supports the device driver interface (DDI). A device driver generates raw device commands when it processes calls to DDI functions made by the graphics engine. The commands are processed by the printer when it prints the image. The syntax, number, and type of these commands vary from device to device.


Default Printing Interface

In addition to GDI and the device driver, the default printing interface consists of several other components that process output before it arrives at the printer. These components are as follows:

  • print spooler
  • print processor
  • graphics engine
  • port monitors


Print Spooler

The primary component of the printing interface is the print spooler. The print spooler is an executable file that manages the printing process. Management of printing involves retrieving the location of the correct printer driver, loading that driver, spooling high-level function calls into a print job, scheduling the print job for printing, and so on. The spooler is loaded at system startup and continues to run until the operating system is shut down.

Applications that print create a printer device context (DC). When an application creates a printer DC, the spooler performs necessary tasks such as determining the location of the required printer driver and then loading the appropriate printer driver. It also determines the data type used to record the print job.

The supported data types include enhanced metafiles (EMF), ASCII text, and raw data (all printer specific data types such as PostScript and PCL). Custom data types can be added to the spooler when additional printer drivers and print processors are installed. A print job is a document stored internally (by using one of the supported data types) that may contain one or more pages of output. It may consist of multiple forms; for example, a job may consist of one envelope and three pages of A4 paper. A print job is defined (or bracketed) by the StartDoc and EndDoc functions.

The default data type for a print job is the enhanced metafile. An EMF record is a compact structure used to store text output commands, raster graphics commands, and so on. When an application calls StartDoc, the spooler creates a spool file and a data file and begins storing EMF records in the spool file. Each time the application calls one of the GDI drawing functions, one or more new EMF records are created and stored in the spool file. The spool and data files are created in an operating system directory. The spooler uses the spool file to store EMF records and uses the data file to record the type of form, the data type for the print job, the target printer, and so on. The spooler deletes these files when the job has successfully printed.


Print Processor

The spooler monitors the current print jobs and the target printer to determine an appropriate time to print a job. Once the spooler determines that a job should be printed, it calls the print processor. The print processor is a DLL that reads EMF records and uses the graphics engine to convert them into DDI calls.

Use the following functions to work with print processors.

Function | Description
AddPrintProcessor | Installs a print processor on a specified server.
DeletePrintProcessor | Removes a printer processor from a specified server.
EnumPrintProcessorDatatypes | Enumerates the data types that a specifed print processor supports.
EnumPrintProcessors | Enumerates the print processors installed on a specified server.
GetPrintProcessorDirectory | Retrieves the path for the print processor on the specified server.


Graphics Engine

The graphics engine is a system DLL that converts print processor output into calls to device driver functions. The sum of these calls for a particular print job is called the journal file. The device driver, in turn, processes the calls in a journal file and converts them into raw device commands that the device can process.


Port Monitors

Once a device driver has converted an entire journal file into raw device commands, the file of converted commands is passed back to the spooler. The spooler sends these low-level commands to a monitor. A port monitor is a .dll that passes the raw device commands over the network, through a parallel port, or through a serial port to the printer device. Custom port monitors can be installed to support passing device data through other communication ports.

Use the following functions to work with port monitors.

Function | Description
AddMonitor | Installs a local port monitor and links the configuration, data, and monitor files.
DeleteMonitor | Removes a port monitor added by the AddMonitor function.
EnumMonitors | Enumerates the port monitors installed on a specified server.


Printer Output

Just as an application requires a display device context (DC) before it can begin drawing in the client area of a window, it needs a printer DC before it can begin sending output to a printer. A printer DC is similar to a display DC in that it is an internal data structure that defines a set of graphic objects and their associated attributes and specifies the graphic modes that affect output. The graphic objects include a pen (for line drawing), a brush (for painting and filling), and a font (for text output).

Unlike a display DC, printer DCs are not owned by the window management component, and they cannot be obtained by calling the GetDC function. Instead, an application must call the CreateDC or PrintDlgEx function.

If you call the CreateDC function, you must supply a driver and port name. To retrieve these names, call the GetPrinter or EnumPrinters function.

If your application calls the PrintDlgEx function and specifies the PD_RETURNDC value in the Flags member of the PRINTDLGEX structure, the system returns a handle to a device context for the printer selected by the user. For more information, see Print Property Sheet and Using the Print Property Sheet.

Microsoft® Windows® 95, Windows 98, and Microsoft Windows NT® versions 4.0 and earlier do not support the PrintDlgEx function. If your application needs to run on these platforms, use the PrintDlg function with the PD_RETURNDC value. For more information, see Print Dialog Box and Displaying the Print Dialog Box.

To set the default printer on Windows 2000, call SetDefaultPrinter. To set the default printer on other operating systems, call GetProfileString, WriteProfileString, and SendNotifyMessage, as shown in the following code snippet:

// Read PrinterPorts from win.ini.Returned string should be of the
// form "driver,port,timeout,timeout", such as "winspool,LPT1:,15,45".

GetProfileString(TEXT("Windows"),TEXT("Device"),_T(",,,"),m_szName, COUNTOF(m_szName));
WriteProfileString(TEXT("Windows"),TEXT("Device"),pszPrinterName ));

// Notify all open applications of the change. Note, only applications // that handle the message will recognize the change.
#if WM_WININICHANGE != WM_SETTINGCHANGE
// Old message type; for Windows 95
SendNotifyMessage(HWND_BROADCAST,WM_WININICHANGE,0,(LPARAM)szWindows);
#endif
// New message type
SendNotifyMessage(HWND_BROADCAST,WM_SETTINGCHANGE,0,(LPARAM)szWindows);

When using this method, you must specify a valid printer, driver, and port. If they are invalid, the APIs do not fail but the result is not defined. This could cause other programs to set the printer back to the previous valid printer. You can use EnumPrinters to retrieve the printer name, driver name, and port name of all available printers.


Printer Escapes

Windows version 3.x supported as many as 64 special functions called printer escapes that applications used to access special device features. An application called these functions by specifying one of 64 predefined values as the second parameter to the Escape function. For example, one of these applications printing on a PostScript printer could draw a PostScript graphic object called a path by calling the Escape function and supplying the BEGIN_PATH and END_PATH values. Most of these escapes are obsolete in the Microsoft® Win32® application programming interface (API) but a few (see discussion following) are provided to simplify the porting of 16-bit Windows-based applications. The Win32 version of GDI supports a complete set of path functions that applications can use instead of the escapes to draw paths on any device. For a list of the Win32 functions that replace some of the escapes, see the Escape function.

Of the 64 original printer escapes, only the QUERYESCSUPPORT and the PASSTHROUGH escapes can be used by Win32-based applications:

Applications written for Windows 3.x can also use QUERYESCSUPPORT and PASSTHROUGH as well as the following 10 escapes. Note that the following escapes are only supported for backward compatibility with Windows 3.x-based applications. The Escape function may fail if a Win32-based application uses any of these:

  • ABORTDOC
  • ENDDOC
  • GETPHYSPAGESIZE
  • GETPRINTINGOFFSET
  • GETSCALINGFACTOR
  • NEWFRAME
  • NEXTBAND
  • SETABORTPROC
  • SETCOPYCOUNT
  • STARTDOC

In addition to supporting Escape, the Win32 API provides an extended escape function called ExtEscape. This function allows applications to access capabilities of a particular device not directly available through GDI.


WYSIWYG Display and Output

Most applications attempt to support WYSIWYG (what you see is what you get) output. This means that text drawn with a 10-point Helvetica bold font in the application window should have a similar appearance when it is printed. Obtaining true WYSIWYG output is virtually impossible and even undesirable in most cases. This is due, in part, to the differences in video and printer technologies; a pixel on a screen is generally larger than a dot on a common laser printer. Viewing distances are different as well; a computer user typically sits about two feet away from the screen, but a reader's eyes are usually one foot or less from the printed page.

To compensate for legibility differences between screens and the printed page, Windows and Windows NT support a unit called the logical inch that is always specified in pixels. For a video display, the logical inch is always greater than the physical inch to compensate for the longer viewing distance and the (generally) coarser resolution. For printers, the logical inch is always equal to the physical inch.

To obtain a WYSIWYG effect when drawing text, an application can use the CreateFont function to specify the font name and size of an ideal (or logical) font and then call the SelectObject function to identify the display or printer device context. When the application calls SelectObject, the system selects a physical font that is the closest possible match to the specified logical font. When the system selects the display font, it chooses a physical font that is larger than the actual size. This occurs because of the larger logical inch on the display. From the user's perspective, however, it appears to be very close to the correct height. When the system selects the font for the printer, it chooses a physical font that is actually the requested size. For more information about fonts and text output, see Fonts and Text.

To obtain a WYSIWYG effect when drawing bitmapped graphics, an application can retrieve the width and height, in logical inches, of the screen and the printed page. Using these values, the application can create horizontal and vertical scaling factors to maintain the proportion of bitmapped images when they are drawn on a printer. For an example that demonstrates this process, see Printing a document. For more information about bitmaps and bitmap output, see Bitmaps.


Per-User DEVMODE

Beginning in Windows 2000, a user can specify the default document settings for a printer. This is called the per-user DEVMODE because it only affects the defaults for a particular user, and the information for each printer is defined in a separate DEVMODE structure. On Windows NT, an application was restricted to the global default that was set by the administrator of the printer. To print a document in a different way, the user had to change the settings manually for each application each time it was launched. On Windows 95/98, a user can do this once at the printer.

To set the per-user DEVMODE, call SetPrinter with either the PRINTER_INFO_2 or the PRINTER_INFO_9 structure. To reset the default to the global default DEVMODE, call SetPrinter with the PRINTER_INFO_8 structure.


Bidi Communication Support

[This is preliminary documentation and subject to change.]

With Whistler, bi-directional printer communication (bidi communication) is provided. This allows drivers and applications to make requests to and get responses from a printer device. Previously, the lack of bi-directional communication limited the ways applications could interact with printers. For example, users had to manually choose installable options because there was no way for applications to configure printers.

The bidi communication support involves two parts: the bidi communication schema and the bidi spooler APIs. The schema describes the requests that an application can make to a device and the format for the requests. The spooler APIs send the requests to the device and also send and receive the bidi data. An application can also send a request to a network print provider for a network printer or a printer that is connected to a remote printer server.


Bidi Communications Schema

[This is preliminary documentation and subject to change.]

The bidi communications schema describes the information about a printer or print server that is available through the bidi spooler APIs. It also describes the format used to get the information. Note that this document explains the pre-defined bidi schema. However, a hardware vendor can extend the schema for special device requirements. For more information, see Extending the Bidi Communications Schema.

To visualize the schema, one can think of its elements as arranged in a tree structure. There is no limit on the depth or breadth of this tree. The following are the definitions for the elements of the schema:

  • Property: A node inside the Property Tree. It can have zero or more children, and can have other properties and data as children. It may contain a list of values or other properties. It can represent a feature, a compound feature or a print system attribute (such as driver name).
  • Data: A single piece or homogeneous list of data. Data is composed of a data name, a data type, and a data value. Data is referenced by data name, and only under properties. For example, "\Printer.Stapler:CurrentValue". Data does not have children. It is a leaf node.
  • Property Path: A path to a property. The '.' is used as the delimiter.
  • Data Path: A path to a data. The ':' is used as the delimiter to indicate retrieval of data.

The schema properties can be grouped in the following way:

  • Alerts: Alerts.
  • Communications: BidiProtocol, ConnectionState, MultiChannel, Manufacturer, Model, Version.
  • Configuration: Memory, PSMemory.
  • Consumables: Consumables.
  • Finishing: Binder, DuplexUnit, Puncher, Stapler.
  • Layout: InputBin.
  • Maintenance: AlignHead, CleanHead.
  • Output: Collate, OutputBin.

The following table describes the details of the bidi schema. If a cell has more than one property, each property can have all of the data in the associated cell. Note that, due the extra depth of the information under the InputBin property, there are additional tables for this information.

Property | Data
Alerts | Accesses alert information. Data is associated with it only through the following child properties:
 | Property | Data
 | AlertX (where X is a positive integer) | Name: Component Type: String Value: Specifies the path to the component Name: Name Type: Keyword Value: Specifies alert information for AlertX. It can be one of the following:
 |  | CoverOpen -- Printer cover is open. MediaSupplyEmpty No toner, no ink, or no paper. MediaSupplyLow Low toner, low ink, or low paper. MediaTrayAlmostFull Output bin is almost full. MediaTrayFull Output bin is full. MediaTrayMissing Input or output bin is missing. PaperJam Paper is jammed in the printer.
AlignHead | Name: Data Type: Binary Value: The binary stream for aligning the printer head.
BidiProtocol | Name: CurrentValue Type: Keyword. Value: The current protocol used in the bidi communication. It can be any of the following Property Names.
 | Property |
 | SNMP PJL IPP10 UPNP |
Binder | Name: CurrentValue Type: Boolean Value: If TRUE, the binder is installed.
CleanHead | Name: Data Type: Binary Value: The binary stream for cleaning the printer head.
Collate | Name: CurrentValue Type: Boolean Value: If TRUE, collation is turned on.
ConnectionState | Name: CurrentValue Type: Keyword. Value: The state of the printer connection. It can be any of the following Property Names:
 | Property |
 | OffLine OnLine Unknown |
Consumables | Accesses toner- and ink-supply information. Data is associated with it only through the following child Properties:
 | Property | Data
 | ConsumableX (where X is a positive integer) | Name: Type Type: Keyword Value: Specifies the type of consumable. It can be either TONER or INK Name: Installed Type: Boolean Value: If TRUE, this consumable is installed. Color: Color Type: Keyword Value: BLACK, CYAN, BLUE Name: Level Type: INT Value: Percentage of the consumable that is available, from 0 to 100.
DuplexUnit | Name: CurrentValue Type: Boolean Value: If TRUE, the duplex unit is installed.
InputBin | Name: CurrentValue Type: Keyword. Value: Information about the input bin. It can be any of the following Property names. Note that each Property has an Installed and a Level value and also two child Properties (referenced in another table).
 | Property |  |  | Data
 | Automatic Bin TopBin MiddleBin BottomBin LargeCapacityBin ManualBin EnvelopeManual EnvelopeBin Tractor PaperCassette LargeFormatPaperBin SmallFormatPaperBin Multi-PurposeBin |  |  | Name: Installed Type: Boolean Value: If TRUE, the tray is installed. Name: Level Type: INT Value: Current paper level as a percentage of total capacity, from 0 to 100. Also see the following topic, "Second-level Properties Under InputBin."
Manufacturer | Name: CurrentValue Type: String Value: The name of the manufacturer. For example, HP.
Memory | Name: CurrentValue Type: INT Value: The number of bytes of installed memory in the printer.
Model | Name: CurrentValue Type: String Value: The model name for the printer. For example, Laserjet 5Si.
MultiChannel | Name: CurrentValue Type: Boolean Value: If TRUE, the language monitor supports multiple channel queries.
OutputBin | Name: CurrentValue Type: Keyword . Value: The current output bin. It can be any of the following Property Names. Note that each Property Name has both an Installed and a Level value.
 | Property |  | Data
 | AutomaticBin TopBin MiddleBin BottomBin Face-UpBin Face-DownBin LargeCapacityBin MailboxBin |  | Name: Installed Type: Boolean Value: If TRUE, the specified tray is installed. Name: Level Type: INT Value: Current paper level as a percentage of total capacity, from 0 to 100.
PSMemory | Name: CurrentValue Type: INT Value: The number of bytes of memory in the PostScript engine.
Puncher | Name: CurrentValue Type: Boolean Value: If TRUE, the puncher is installed.
Stapler | Name: CurrentValue Type: Boolean Value: If TRUE, the stapler is installed.
Version | Name: CurrentValue Type: INT Value: The version number of the bidi schema.

Second-level Properties Under InputBin

These are the child properties of each of the properties under InputBin.

Property | Data
MediaType | Name: CurrentValue Type: Keyword Value: The medium on which the image is printed. It can be any of the following:
 | Property |
 | Unspecified BackPrintFilm Bond CardStock Color Envelope FabricSheet Glossy GlossyPhotoCard GlossyPhotoFilm Heavy | HighGlossPhotoFilm HighResolutionPaper Label Letterhead Plain Pre-printed Pre-punched Recycled Transparency T-shirtTransfer
PaperSize | Name: CurrentValue Type: Keyword Value: Paper size. It can be any Property name from the following table.

These are child properties under PaperSize (see table above).

Property
9x11 (9 x 11 in)
10x11 (10 x 11 in)
10x14 (10 x 14 in)
11x17 (11 x 17 in)
12x11 (12 x 11 in)
15x11 (15 x 11 in)
A2 (420 x 594 mm)
A3 (297 x 420 mm)
A3 Extra (322 x 445 mm)
A3 Extra Transverse (322 x 445 mm)
A3 Rotated (420 x 297 mm)
A3 Transverse (297 x 420 mm)
A4 (210 x 297 mm)
A4 Extra (9.27 x 12.69 in)
A4 Plus (210 x 330 mm)
A4 Rotated (297 x 210 mm)
A4 Rotated (297 x 210 mm)
A4 Transverse (210 x 297 mm)
A5 (148 x 210 mm)
A5 Extra (174 x 235 mm)
A5 Rotated (210 x 148 mm)
A5 Transverse (148 x 210 mm)
A6 (105 x 148 mm)
A6 Rotated (148 x 105 mm)
B4 (ISO) (250 x 353 mm)
B4 (JIS) (250 x 354 mm)
B4 (JIS) Rotated (364 x 257 mm)
B5 (ISO) Extra (201 x 276 mm)
B5 (JIS) (182 x 257 mm)
B5 (JIS) Rotated (257 x 182 mm)
B5 (JIS) Transverse (182 x 257 mm)
B6 (JIS) (128 x 182 mm)
B6 (JIS) Rotated (182 x 128 mm)
C size sheet (17 x 22 in)
D size sheet (22 x 34 in)
E size sheet (34 x 44 in)
Envelope #9 (3 7/8 x 8 7/8 in)
Envelope #10 (4 1/8 x 9 1/2 in)
Envelope #11 (4 1/2 x 10 3/8 in)
Envelope #12 (4 1/2 x 11 in)
Envelope #14 (5 x 11 1/2 in)
Envelope B4 (250 x 353 mm)
Envelope B5 (176 x 250 mm)
Envelope B6 (176 x 125 mm)
Envelope C3 (324 x 458 mm)
Envelope C4 (229 x 324 mm)
Envelope C5 (162 x 229 mm)
Envelope C6 (114 x 162 mm)
Envelope C65 (114 x 229 mm)
Envelope DL (110 x 220mm)
Envelope Invite (220 x 220 mm)
Envelope Italy (110 x 230 mm)
Envelope Monarch (3.875 x 7.5 in)
Envelope Personal (3 5/8 x 6 1/2 in)
Executive (7 1/4 x 10 1/2 in)
Folio (8 1/2 x 13 in)
German Std Fanfold (8 1/2 x 12 in)
German Legal Fanfold (8 1/2 x 13 in)
Japanese Postcard (100 x 148 mm)
Japanese Double Postcard (200 x 148 mm)
Japanese Envelope Kaku #2 (240 x 332 mm)
Japanese Envelope Kaku #3 (216 x 277 mm)
Japanese Envelope Chou #3 (120 x 235 mm) 		Japanese Envelope Chou #4 (90 x 205 mm)
Japanese Envelope Kaku #2 Rotated (332 x 240 mm)
Japanese Envelope Kaku #3 Rotated (277 x 216 mm)
Japanese Envelope Chou #3 Rotated (205 x 90 mm)
Japanese Envelope Chou #4 Rotated (235 x 120 mm)
Japanese Envelope You #4 (105 x 235 mm)
Japanese Envelope You #4 Rotated (235 x 105 mm)
Japanese Postcard Rotated (148 x 100 mm)
Double Japanese Postcard Rotated (148 x 200 mm)
Ledger (17 x 11 in)
Legal (8 1/2 x 14 in)
Legal Extra (9 1/2 x 15 in)
Letter (8 1/2 x 11 in)
Letter Extra (9 1/2 x 12 in)
Letter Extra Transverse (9 1/2 x 12 in)
Letter Plus (8.5 x 12.69 in)
Letter Rotated (11 x 8 1/2 11 in)
Letter Small (8 1/2 x 11 in)
Letter Transverse (8 1/2 x 11 in)
Note (8 1/2 x 11 in)
PRC 16K (146 x 215 mm)
PRC 32K (97 x 151 mm)
PRC 32K(Big) (97 x 151 mm)
PRC Envelope #1 (102 x 165 mm)
PRC Envelope #2 (102 x 176 mm)
PRC Envelope #3 (125 x 176 mm)
PRC Envelope #4 (110 x 208 mm)
PRC Envelope #5 (110 x 220 mm)
PRC Envelope #6 (120 x 230 mm)
PRC Envelope #7 (160 x 230 mm)
PRC Envelope #8 (120 x 309 mm)
PRC Envelope #9 (229 x 324 mm)
PRC Envelope #10 (324 x 458 mm)
PRC 16K Rotated (260 x 188 mm)
PRC 32K Rotated (184 x 130 mm)
PRC 32K(Big) Rotated (102 x 140 mm)
PRC Envelope #1 Rotated (165 x 102 mm)
PRC Envelope #2 Rotated (176 x 102 mm)
PRC Envelope #3 Rotated (176 x 125 mm)
PRC Envelope #4 Rotated (208 x 110 mm)
PRC Envelope #5 Rotated (220 x 110 mm)
PRC Envelope #6 Rotated (230 x 120 mm)
PRC Envelope #7 Rotated (230 x 160 mm)
PRC Envelope #8 Rotated (309 x 120 mm)
PRC Envelope #9 Rotated (324 x 229 mm)
PRC Envelope #10 Rotated (458 x 324 mm)
Quarto 215 x 275 mm
Statement (5 1/2 x 8 1/2 in)
SuperA (227 x 356 mm)
SuperB (305 x 487 mm)
Tabloid (11 x 17 in)
Tabloid Extra (11.69 x 18 in)
US Std Fanfold (14 7/8 x 11 in)

Accessing the Schema Information

To access the printer information, use the schema to construct a string that identifies the information you want. Then use the appropriate bidi spooler APIs with the constructed string. For the pre-defined schema, such a string begins with "\Printer.", then any subordinate property names until you reach the desired property, and finally the data name. Use a period (.) to separate each property name, and use a colon (:) before the data name.

For example, to see if the printer supports stapling, use

"\Printer.Stapler:CurrentValue"

To see which bin is the current input bin, use

"\Printer.InputBin:CurrentValue"

To see if the top input bin is installed, use

"\Printer.InputBin.TopBin:Installed"

To determine the media type in the top input bin, use:

"\Printer.InputBin.TopBin.MediaType:CurrentValue"


Extending the Bidi Communications Schema

[This is preliminary documentation and subject to change.]

The current schema is minimal set of properties and data for printer communication. It is intended that independent hardware vendors (IHV) define new properties and data to extend the applicability of the schema. For example, the current schema does not deal with scanners or fax machines; an IHV may want to develop the schema for these devices. These new properties and data can be private to the creator or they can be added to the standard well-known set. Thus, not all parties who manipulate a property tree need to understand all properties and data in the tree. There is no limit on the extensibility; new properties and data can be integrated into any areas of the existing schema.

Any extensions must conform to the following guidelines:

  • The printer schema starts with "\Printer." To extend the schema to support scanners or faxes, IHVs must use "\Scanner." or "\Fax."
  • When adding a new property, a property name is required. It is the keyword name of the property.
  • When adding new data, the following are required:
    Data Name: The keyword name for the data.
    Data Type: The type of the data.
    Data Value: The enumeration of possible data associated with the data.
    For example, there could be a new data called AngleZ, where Get("\Printer.NewStapler.AngleZ") returns a data of type INT and a data value of 90 degrees.
  • A private property or data must have a prefix in order to prevent name collision. For example, a company is an appropriate prefix. A name prefix is not required for a nominated new standard droperty or data.
  • Backward Compatibility: Any application or print system component that introduces non-standard or standard properties and data must maintain backward compatibility with old properties and data with the same or similar meaning to preserve semantics.


Using the Printing Functions

The examples in this section demonstrate how to print text and graphics:

  • Retrieving a Printer Device Context
  • Preparing to Print
  • Printing a Document
  • Sending Data Directly to a Printer
  • Using the Bidi Schema to Query a Device


Retrieving a Printer Device Context

When the user selects the Print option in the File menu, you can call the PrintDlgEx function to display the Print property sheet. The property sheet enables the user to provide information about the print job. For example, the user can specify a range of pages to print, the number of copies, and so on. In addition, PrintDlgEx can retrieve a handle to a device context for the selected printer. You can use the handle to render output on the printer. The PrintDlgEx function is available on Windows 2000 and later. For sample code that illustrates the use of PrintDlgEx to retrieve a printer device context, see Using the Print Property Sheet.

If your application needs to run on Windows 95/98, or Windows NT versions 4.0 and earlier, use the PrintDlg function. For sample code that illustrates the use of PrintDlg to retrieve a printer device context, see Displaying the Print Dialog Box.


Preparing to Print

The following code sample calls the GetDeviceCaps function with the RASTERCAPS value to determine whether the selected printer is capable of printing bitmaps. If the GetDeviceCaps return value indicates that the printer does not support StretchDIBits, the sample displays a message box to inform the user. Note that when targetting a printer DC, you should use a DIB instead of a DDB.

// Examine the raster capabilities of the device identified by pd.hDC
// to verify that it supports the StretchDIBits function.

if (!(GetDeviceCaps(pd.hDC, RASTERCAPS)
    & RC_StretchDIB))
{
    DeleteDC(pd.hDC);
    MessageBox(hwnd,
        "Printer does not support StretchDIBits.",
        "Device Error",
        MB_OK);
    break;
}

After the sample application determines that the selected printer is capable of printing bitmaps, it follows these steps:

  1. Sets a Boolean flag that the application's abort procedure can examine to determine whether to allow printing to continue.
  2. Registers the application's AbortProc function, which is used to cancel a print job.
  3. Displays a modeless Cancel dialog box.
  4. Disables the application's window while the dialog box is displayed.

These steps are illustrated in the following code sample.

// Set the flag used by the AbortPrintJob dialog procedure.

bPrint = TRUE;

// Register the application's AbortProc function with GDI.

SetAbortProc(pd.hDC, AbortProc);

// Display the modeless Cancel dialog box.

hdlgCancel = CreateDialog(hinst, (LPTSTR) "AbortDlg",
    hwnd, (DLGPROC) AbortPrintJob);

// Disable the application's window.

EnableWindow(hwnd, FALSE);

Once the application registers the AbortProc abort procedure, GDI calls the function periodically during the printing process to determine whether to cancel the job. If the user chooses to cancel the job, GDI notifies the spooler that it should delete the corresponding journal file from the print queue and reset the printer to its default state.


Abort Procedure

Any Windows-based application that supports printing should provide an abort procedure and a modeless dialog box that allows a user to cancel a print job. The abort procedure for the sample application contains a message loop that retrieves messages for the modeless dialog box.

BOOL CALLBACK AbortProc(HDC hdc, int nCode)
{
    MSG msg;

    // Retrieve and remove messages from the thread's message queue.

    while (PeekMessage((LPMSG) &msg, (HWND) NULL, 0, 0, PM_REMOVE))
    {
        // Process any messages for the Cancel dialog box.

        if (!IsDialogMessage(hdlgCancel, (LPMSG) &msg))
        {
            TranslateMessage((LPMSG) &msg);
            DispatchMessage((LPMSG) &msg);
        }
    }

    // Return the global bPrint flag, which is initially set to TRUE.
    // The dialog box procedure for the Cancel dialog box
    // sets bPrint to FALSE if the user presses the Cancel button.

    return bPrint;

}

For Win16-based applications, this procedure must be exported in the application's module-definition (.def) file.


Cancel Dialog Box

The Cancel dialog box typically contains a single push button that allows the user to cancel a print job. The following example shows a resource file template for a Cancel dialog box.

AbortDlg DIALOG LOADONCALL MOVEABLE DISCARDABLE 33, 32, 160, 70

CAPTION "Sample Printing App"

STYLE WS_BORDER | WS_CAPTION | WS_DLGFRAME | WS_VISIBLE |
      WS_POPUP | WS_SYSMENU

BEGIN

    CONTROL "Now Printing: ", IDD_TEXT, "static",
        SS_CENTER | WS_CHILD, 0, 10, 160, 8

    CONTROL "", IDD_FILE, "static",
        SS_CENTER | WS_CHILD, 0, 25, 160, 8

    CONTROL "Cancel", IDD_CANCEL, "button",
        BS_DEFPUSHBUTTON | WS_TABSTOP | WS_CHILD,
        60, 45, 45, 15

END

The code sample that follows shows a typical dialog box procedure for the Cancel dialog box.

LRESULT CALLBACK AbortPrintJob(
        HWND hwndDlg,     // handle to dialog box
        UINT message,     // type of message
        WPARAM wParam,    // message-specific information
        LPARAM lParam)    // message-specific information
{
    switch (message)
    {
        case WM_INITDIALOG:  / message: initialize dialog box

            // Initialize the static text control.

            SetDlgItemText(hwndDlg, IDD_FILE, ofn.lpstrFile);

            return TRUE;

        case WM_COMMAND:     // message: received a command

            bPrint = FALSE;

            return TRUE;

        default:
            return FALSE;

    }
        UNREFERENCED_PARAMETER(lParam);
        UNREFERENCED_PARAMETER(wParam);
}


Printing a Document

Once the application initializes the necessary variables, registers its AbortProc function, and displays its modeless Cancel dialog box, it can start the print job by calling the StartDoc function.

After the application begins a print job, it can define individual pages in the document by calling the StartPage and EndPage functions and embedding the appropriate calls to GDI drawing functions within this bracket. After the application has defined the last page, it can close the document and end the print job by calling the EndDoc function.

The following example shows the code required to print a string of text and a bitmapped image. The string of text, centered at the top of the page, identifies the path and file name for the file that contains the bitmapped image. The bitmapped image, centered vertically and horizontally on the page, is drawn so that the same proportions used to draw the image in the application's window are maintained. Note that when targetting a printer DC, use a DIB instead of a DDB -- that is why StretchDIBits is used in this code.

    // Zero and then initialize the members of a DOCINFO structure.

    memset( &di, 0, sizeof(DOCINFO) );
    di.cbSize = sizeof(DOCINFO);
    di.lpszDocName = "Bitmap Printing Test";
    di.lpszOutput = (LPTSTR) NULL;
    di.lpszDataType = (LPTSTR) NULL;
    di.fwType = 0;

    // Begin a print job by calling the StartDoc function.

    nError = StartDoc(pd.hDC, &di);
    if (nError == SP_ERROR)
    {
        errhandler("StartDoc", hwnd);
        goto Error;
    }

    // Inform the driver that the application is about to begin
    // sending data.

    nError = StartPage(pd.hDC);
    if (nError <= 0)
    {
        errhandler("StartPage", hwnd);
        goto Error;
    }

    // Retrieve the number of pixels-per-logical-inch in the
    // horizontal and vertical directions for the display upon which
    // the bitmap was created. These are likely the same as for
    // the present display, so we use those values here.

    hWinDC = GetDC(hWnd);
    fLogPelsX1 = (float) GetDeviceCaps(hWinDC, LOGPIXELSX);
    fLogPelsY1 = (float) GetDeviceCaps(hWindDC, LOGPIXELSY);

    // Retrieve the number of pixels-per-logical-inch in the
    // horizontal and vertical directions for the printer upon which
    // the bitmap will be printed.

    fLogPelsX2 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSX);
    fLogPelsY2 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSY);

    // Determine the scaling factors required to print the bitmap and
    // retain its original proportions.

    if (fLogPelsX1 > fLogPelsX2)
        fScaleX = (fLogPelsX1 / fLogPelsX2);
    else fScaleX = (fLogPelsX2 / fLogPelsX1);

    if (fLogPelsY1 > fLogPelsY2)
        fScaleY = (fLogPelsY1 / fLogPelsY2);
    else fScaleY = (fLogPelsY2 / fLogPelsY1);

    // Compute the coordinates of the upper left corner of the
    // centered bitmap.

    cWidthPels = GetDeviceCaps(pd.hDC, HORZRES);
    xLeft = ((cWidthPels / 2) - ((int) (((float) bmih.biWidth)
            * fScaleX)) / 2);
    cHeightPels = GetDeviceCaps(pd.hDC, VERTRES);
    yTop = ((cHeightPels / 2) - ((int) (((float) bmih.biHeight)
            * fScaleY)) / 2);

    // Use StretchDIBits to scale the bitmap and maintain
    // its original proportions (that is, if the bitmap was square
    // when it appeared in the application's client area, it should
    // also appear square on the page).

    if (StretchDIBits(pd.hDC, xLeft, yTop, (int) ((float) bmih.biWidth
        * fScaleX), (int) ((float) bmih.biHeight * fScaleY), 0, 0,
        bmih.biWidth, bmih.biHeight, lpBits, lpBitsInfo, iUsage,
        SRCCOPY) == GDI_ERROR)
    {
        errhandler("StretchDIBits Failed", hwnd);
    }

    // Retrieve the width of the string that specifies the full path
    // and filename for the file that contains the bitmap.

    GetTextExtentPoint32(pd.hDC, ofn.lpstrFile,
        ofn.nFileExtension + 3, &szMetric);

    // Compute the starting point for the text-output operation. The
    // string will be centered horizontally and positioned three lines
    // down from the top of the page.

    xLeft = ((cWidthPels / 2) - (szMetric.cx / 2));
    yTop = (szMetric.cy * 3);

    // Print the path and filename for the bitmap, centered at the top
    // of the page.

    TextOut(pd.hDC, xLeft, yTop, ofn.lpstrFile,
        ofn.nFileExtension + 3);

    // Determine whether the user has pressed the Cancel button in the
    // AbortPrintJob dialog box; if the button has been pressed, call
    // the AbortDoc function. Otherwise, inform the spooler that the
    // page is complete.

    nError = EndPage(pd.hDC);

    if (nError <= 0)
    {
        errhandler("EndPage", hwnd);
        goto Error;
    }

    // Inform the driver that document has ended.

    nError = EndDoc(pd.hDC);
    if (nError <= 0)
        errhandler("EndDoc", hwnd);

Error:
    // Enable the application's window.

    EnableWindow(hwnd, TRUE);

    // Remove the AbortPrintJob dialog box.

    DestroyWindow(hdlgCancel);

    // Delete the printer DC.

    DeleteDC(pd.hDC);

Because the pixels on a screen typically have different dimensions than the dots on a printer, it is necessary to scale bitmapped images to obtain a WYSIWYG effect. This is done by obtaining horizontal and vertical scaling factors and then applying those factors to the width and height values passed to the StretchDIBits function. In the sample application, the scaling factors were obtained by retrieving the horizontal and vertical logical-pixel count for the two devices. Once the scaling factors were obtained, they were used to adjust the bitmap width and height.

To center the bitmap on the page, the application first computed the width and height of the scaled bitmap. (The bitmap was scaled to maintain the original proportions of the image.) These values were divided by two and then subtracted from half of the width and height of the page. The result defines the coordinates of the upper-left corner of the bitmap.

To center the text at the top of the page, the application called the GetTextExtentPoint32 function to retrieve the width and height of the string specifying the path names and file names. Once these values were obtained, the application used the height to position the string three lines down the page and the width to position the string horizontally centered on the page.

The following illustration shows a representation of the page that appeared when the application printed the bitmapped image in the Winlogo.bmp file. This illustration also depicts the variables used to position the text and to position and scale the bitmap.


Sending Data Directly to a Printer

It is sometimes necessary to bypass the driver and send printer-specific data directly to a printer. The following code shows how this can be done for both local and networked printers by using Win32 functions. This method can be used to replace the PASSTHROUGH escape and SpoolFile() methods.

      // RawDataToPrinter - sends binary data directly to a printer
      //
      // szPrinterName: NULL-terminated string specifying printer name
      // lpData:        Pointer to raw data bytes
      // dwCount        Length of lpData in bytes
      //
      // Returns: TRUE for success, FALSE for failure.
      //
       BOOL RawDataToPrinter(LPSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
      {
        HANDLE     hPrinter;
        DOC_INFO_1 DocInfo;
        DWORD      dwJob;
        DWORD      dwBytesWritten;

        // Need a handle to the printer.
        if( ! OpenPrinter( szPrinterName, &hPrinter, NULL ) )
          return FALSE;

        // Fill in the structure with info about this "document."
        DocInfo.pDocName = "My Document";
        DocInfo.pOutputFile = NULL;
        DocInfo.pDatatype = "RAW";
        // Inform the spooler the document is beginning.
        if( (dwJob = StartDocPrinter( hPrinter, 1, (LPSTR)&DocInfo )) == 0 )
        {
          ClosePrinter( hPrinter );
          return FALSE;
        }
        // Start a page.
        if( ! StartPagePrinter( hPrinter ) )
        {
          EndDocPrinter( hPrinter );
          ClosePrinter( hPrinter );
          return FALSE;
        }
        // Send the data to the printer.
        if( !WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten ) )
        {
          EndPagePrinter( hPrinter );
          EndDocPrinter( hPrinter );
          ClosePrinter( hPrinter );
          return FALSE;
        }
        // End the page.
        if( ! EndPagePrinter( hPrinter ) )
        {
          EndDocPrinter( hPrinter );
          ClosePrinter( hPrinter );
          return FALSE;
        }
        // Inform the spooler that the document is ending.
        if( ! EndDocPrinter( hPrinter ) )
        {
          ClosePrinter( hPrinter );
          return FALSE;
        }
        // Tidy up the printer handle.
        ClosePrinter( hPrinter );
        // Check to see if correct number of bytes were written.
        if( dwBytesWritten != dwCount )
          return FALSE;
        return TRUE;
      }


Using the Bidi Schema to Query a Device

This sample code shows how you can implement a client to retrieve bidi information from a device. In particular, it illustrates how you can query a device

#include "bidispl.h"

IBidiSpl * pIBidiSpl = NULL ;
IBidiRequest * pRequest = NULL;
hr = CoInitializeEx (NULL, COINIT_MULTITHREADED) ;
hr = CoCreateInstance(CLSID_BidiSpl,
                      NULL,
                      CLSCTX_INPROC_SERVER,
                      IID_IBidiSpl,
                      (void**)&pIBidiSpl) ;
hr = pIBidiSpl->BindDevice (pPrinter, dwAccess);
hr = CoCreateInstance(CLSID_BidiRequest,
                      NULL,
                      CLSCTX_INPROC_SERVER,
                      IID_IBidiRequest,
                      (void**)&pIReq) ;
hr = plReq->SetSchema (L"\\Printer.DuplexUnit:CurrentValue");
hr = pIBidiSpl->SendRecv (BIDI_ACTION_GET, pRequest);
hr = pIReq->GetOutputData (0,
                           &pszSchema,
                           &dwType,
                           &pData,
                           &uSize);
if (dwType == BIDI_BOOL) {
bDuplexInstalled = *(PBOOL)pData;
}
CoTaskMemFree (pData);
hr = pIBidiSpl->UnbindDevice ();
pRequest->Release ();
pIbididSpl->Release ();
CoUninitialize ();


Printing and Print Spooler Reference

The following elements are associated with printing and the print spooler:

  • Printing and Print Spooler Functions
  • Printing and Print Spooler Structures
  • Printing and Print Spooler Messages
  • Printer Escape Functions
  • Bidi Communication Interfaces_win32_Bidi_Communication_Interfaces


Printing and Print Spooler Functions

The following functions are used to print.

Function | Description
AbortDoc | Stops the current print job and erases everything drawn since the last call to the StartDoc function.
DeviceCapabilities | Retrieves the capabilities of a printer device driver.
EndDoc | Ends a print job.
EndPage | Notifies the device that the application has finished writing to a page.
Escape | Enables applications to access capabilities of a particular device that are not available through GDI.
ExtEscape | Enables applications to access capabilities of a particular device that are not available through GDI.
SetAbortProc | Sets the application-defined abort function that allows a print job to be canceled during spooling.
StartDoc | Starts a print job.
StartPage | Prepares the printer driver to accept data.

The following functions are used to access the print spooler.

Function | Description
AbortPrinter | Deletes a printer's spool file if the printer is configured for spooling.
AbortProc | An application-defined callback function used with the SetAbortProc function.
AddForm | Adds a form to the list of available forms that can be selected for the specified printer.
AddJob | Adds a print job to the list of print jobs that can be scheduled by the print spooler.
AddMonitor | Installs a local port monitor and links the configuration, data, and monitor files.
AddPort | Adds the name of a port to the list of supported ports.
AddPrinter | Adds a printer to the list of supported printers for a specified server.
AddPrinterConnection | Adds a connection to the specified printer for the current user.
AddPrinterDriver | Installs a local or remote printer driver and links the configuration, data, and driver files.
AddPrinterDriverEx | Installs a local or remote printer driver and links the configuration, data, and driver files.
AddPrintProcessor | Installs a print processor on the specified server and adds the print-processor name to an internal list of supported print processors.
AddPrintProvidor | Installs a local print provider and links the configuration, data, and provider files.
AdvancedDocumentProperties | Displays a printer-configuration dialog box for the specified printer, allowing the user to configure that printer.
ClosePrinter | Closes the specified printer object.
ConfigurePort | Displays the port-configuration dialog box for a port on the specified server.
ConnectToPrinterDlg | Displays a dialog box that lets users browse and connect to printers on a network.
DeleteForm | Removes a form name from the list of supported forms.
DeleteMonitor | Removes a port monitor added by the AddMonitor function.
DeletePort | Displays a dialog box that allows the user to delete a port name.
DeletePrinter | Deletes the specified printer object.
DeletePrinterConnection | Deletes a connection to a printer.
DeletePrinterData | Deletes specified configuration data for a printer.
DeletePrinterDataEx | Deletes a specified value from the configuration data for a printer.
DeletePrinterDriver | Removes the specified printer-driver name from the list of names of supported drivers for a server.
DeletePrinterDriverEx | Removes the specified printer-driver name from the list of names of supported drivers for a server and deletes the files associated with the driver.
DeletePrinterKey | Deletes a specified key and all its subkeys for a specified printer.
DeletePrintProcessor | Removes a printer processor.
DeletePrintProvidor | Removes a local print provider.
DocumentProperties | Retrieves or modifies printer initialization information or displays a printer-configuration property sheet for the specified printer.
EndDocPrinter | Ends a print job for the specified printer.
EndPagePrinter | Notifies the print spooler that the application is at the end of a page in a print job.
EnumForms | Enumerates the forms supported by the specified printer.
EnumJobs | Retrieves information about a specified set of print jobs for a specified printer.
EnumMonitors | Retrieves information about the port monitors installed on the specified server.
EnumPorts | Enumerates the ports that are available for printing on a specified server.
EnumPrinterData | Enumerates configuration data for a specified printer.
EnumPrinterDataEx | Enumerates all value names and data for a specified printer and key.
EnumPrinterDrivers | Enumerates the printer drivers installed on a specified printer server.
EnumPrinterKey | Enumerates the subkeys of a specified key for a specified printer.
EnumPrinters | Enumerates available printers, print servers, domains, or print providers.
EnumPrintProcessorDatatypes | Enumerates the data types that a specifed print processor supports.
EnumPrintProcessors | Enumerates the print processors installed on the specified server.
FindClosePrinterChangeNotification | Closes a change notification object.
FindFirstPrinterChangeNotification | Creates a change notification object.
FindNextPrinterChangeNotification | Retrieves information about the most recent change notification for a change notification object.
FlushPrinter | Sends a buffer to the printer in order to clear it from a transient state.
FreePrinterNotifyInfo | Frees a system-allocated buffer created by the FindNextPrinterChangeNotification function.
GetDefaultPrinter | Retrieves the printer name of the default printer for the current user on the local computer.
GetForm | Retrieves information about a specified form.
GetJob | Retrieves information about a specified print job.
GetPrinter | Retrieves information about a specified printer.
GetPrinterData | Retrieves configuration data for the specified printer or print server.
GetPrinterDataEx | Retrieves configuration data for the specified printer or print server.
GetPrinterDriver | Retrieves driver data for the specified printer.
GetPrinterDriverDirectory | Retrieves the path of the printer-driver directory.
GetPrintProcessorDirectory | Retrieves the path for the print processor on the specified server.
OpenPrinter | Retrieves a handle to the specified printer or print server.
PrinterProperties | Displays a printer-properties property sheet for the specified printer.
PrintWindow | Copies a visual window to a device context.
ReadPrinter | Retrieves data from the specified printer.
ResetPrinter | Specifies the data type and device mode values to be used for printing documents submitted by the StartDocPrinter function.
ScheduleJob | Requests that the print spooler schedule a specified print job for printing.
SetDefaultPrinter | Sets the printer name of the default printer for the current user on the local computer.
SetForm | Sets the form information for the specified printer.
SetJob | Pauses, resumes, cancels, or restarts a print job on a specified printer.
SetPort | Sets the status associated with a printer port.
SetPrinter | Sets the data for a specified printer or sets the state of the specified printer by pausing printing, resuming printing, or clearing all print jobs.
SetPrinterData | Sets the configuration data for a printer or print server.
SetPrinterDataEx | Sets the configuration data for a printer or print server.
StartDocPrinter | Notifies the print spooler that a document is to be spooled for printing.
StartPagePrinter | Notifies the spooler that a page is about to be printed on the specified printer.
WritePrinter | Notifies the print spooler that data should be written to the specified printer.


AbortDoc

The AbortDoc function stops the current print job and erases everything drawn since the last call to the StartDoc function.

int AbortDoc(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context for the print job.

Return Values

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is SP_ERROR.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

Applications should call the AbortDoc function to stop a print job if an error occurs, or to stop a print job after the user cancels that job. To end a successful print job, an application should call the EndDoc function.

If Print Manager was used to start the print job, calling AbortDoc erases the entire spool job, so that the printer receives nothing. If Print Manager was not used to start the print job, the data may already have been sent to the printer. In this case, the printer driver resets the printer (when possible) and ends the print job.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EndDoc, SetAbortProc, StartDoc


AbortPrinter

The AbortPrinter function deletes a printer's spool file if the printer is configured for spooling.

BOOL AbortPrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in] Handle to the printer from which the spool file is deleted. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If the printer is not configured for spooling, the AbortPrinter function has no effect.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter


AbortProc

The AbortProc function is an application-defined callback function used with the SetAbortProc function. It is called when a print job is to be canceled during spooling. The ABORTPROC type defines a pointer to this callback function. AbortProc is a placeholder for the application-defined function name.

BOOL CALLBACK AbortProc(
  HDC hdc,     // handle to DC
  int iError   // error value
);

Parameters

hdc
[in] Handle to the device context for the print job.
iError
[in] Specifies whether an error has occurred. This parameter is zero if no error has occurred; it is SP_OUTOFDISK if Print Manager is currently out of disk space and more disk space will become available if the application waits.

Return Values

The callback function should return TRUE to continue the print job or FALSE to cancel the print job.

Remarks

If the iError parameter is SP_OUTOFDISK, the application need not cancel the print job. If it does not cancel the job, it must yield to Print Manager by calling the PeekMessage or GetMessage function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetMessage, PeekMessage, SetAbortProc


AddForm

The AddForm function adds a form to the list of available forms that can be selected for the specified printer.

BOOL AddForm(
  HANDLE hPrinter,  // handle to printer object
  DWORD Level,      // data-structure level
  LPBYTE pForm      // form information buffer
);

Parameters

hPrinter
[in] Handle to the printer that supports printing with the specified form. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the level of the structure to which pForm points. This value must be 1.
pForm
[in] Pointer to a FORM_INFO_1 structure.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application can determine which forms are available for a printer by calling the EnumForms function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EnumForms, FORM_INFO_1, OpenPrinter


AddJob

The AddJob function adds a print job to the list of print jobs that can be scheduled by the print spooler. The function retrieves the name of the file you can use to store the job.

BOOL AddJob(
  HANDLE hPrinter,   // handle to printer
  DWORD Level,       // print job information version
  LPBYTE pData,      // job information buffer
  DWORD cbBuf,       // size of job information buffer
  LPDWORD pcbNeeded  // bytes received or required
);

Parameters

hPrinter
[in] Handle that specifies the printer for the print job. This must be a local printer that is configured as a spooled printer. If hPrinter is a handle to a remote printer connection, or if the printer is configured for direct printing, the AddJob function fails. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the version of the print job information data structure that the function stores into the buffer pointed to by pData. Set this parameter to one.
pData
[out] Pointer to a buffer that receives an ADDJOB_INFO_1 data structure and a path string.
cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pData. The buffer needs to be large enough to contain an ADDJOB_INFO_1 structure and a path string.
pcbNeeded
[out] Pointer to a variable that receives the total size, in bytes, of the ADDJOB_INFO_1 data structure plus the path string. If this value is less than or equal to cbBuf and the function succeeds, this is the actual number of bytes written to the buffer pointed to by pData. If this number is greater than cbBuf, the buffer is too small, and you must call the function again with a buffer size at least as large as *pcbNeeded.

Windows 95/98/Me: pcbNeeded returns the correct number only if cbBuf is greater than zero and less than sizeof(ADDJOB) + sizeof(path string). Otherwise it returns an incorrect number.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Windows 95/98/Me: The following table shows how cbBuf affects AddJob.

Condition | Result
cbBuf = zero | Function fails with ERROR_INVALID_USER_BUFFER, pcbNeeded returns incorrect number.
cbBuf >= sizeof (ADDJOB_INFO_1 + path string) | Function succeeds but pcbNeeded returns an incorrect number.
zero < cbBuf < sizeof (ADDJOB_INFO_1 + path string) | Function fails and pcbNeeded returns the correct number.

Remarks

You can call the CreateFile function to open the spool file specified by the Path member of the ADDJOB_INFO_1 structure, and then call the WriteFile function to write print job data to it. Once that is done, call the ScheduleJob function to notify the print spooler that the print job can now be scheduled by the spooler for printing.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, ADDJOB_INFO_1, CreateFile, OpenPrinter, ScheduleJob, WriteFile


AddMonitor

The AddMonitor function installs a local port monitor and links the configuration, data, and monitor files.

BOOL AddMonitor(
  LPTSTR pName,      // server name
  DWORD Level,       // monitor information level
  LPBYTE pMonitors   // monitor information buffer
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the monitor should be installed. For this release of Windows NT, monitors may only be installed locally, so this string should be NULL.
Level
[in] Specifies the version of the structure to which pMonitors points. This value must be 2.
pMonitors
[in] Pointer to a MONITOR_INFO_2 structure. If the pEnvironment member of the pMonitors structure is NULL, the current environment of the caller (client), not of the destination (server), is used.

Windows 95/98/Me: pEnvironment must not be NULL. Instead, the recommended value is "Windows 4.0".

Note that the call will fail if the environment does not match the environment of the server, that is, you can only add a monitor that was written for the architecture of the server.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before an application calls the AddMonitor function, all files required by the monitor must be copied to the SYSTEM32 directory.

To determine the port monitors that are currently installed, call the EnumMonitors function.

To remove a monitor added by AddMonitor, call the DeleteMonitor function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeleteMonitor, EnumMonitors, MONITOR_INFO_2


AddPort

The AddPort function adds the name of a port to the list of supported ports. The AddPort function is exported by the port monitor.

BOOL AddPort(
  LPTSTR pName,         // server name
  HWND hWnd,            // handle to parent window
  LPTSTR pMonitorName   // monitor name
);

Parameters

pName
[in] Pointer to a zero-terminated string that specifies the name of the server to which the port is connected. If this parameter is NULL, the port is local.
hWnd
[in] Handle to the parent window of the AddPort dialog box.
pMonitorName
[in] Pointer to a zero-terminated string that specifies the monitor associated with the port.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The AddPort function browses the network to find existing ports, and displays a dialog box for the user. The AddPort function should validate the port name entered by the user by calling EnumPorts to ensure that no duplicate names exist.

The caller of the AddPort function must have SERVER_ACCESS_ADMINISTER access to the server to which the port is connected.

To add a port without displaying a dialog box, call the XcvData function instead of AddPort. For more information about XcvData, see the Microsoft Windows 2000 Driver Development Kit.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePort EnumPorts SetPort


AddPrinter

The AddPrinter function adds a printer to the list of supported printers for a specified server.

HANDLE AddPrinter(
  LPTSTR pName,     // server name
  DWORD Level,      // printer information level
  LPBYTE pPrinter   // printer information buffer
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the printer should be installed. If this string is NULL, the printer is installed locally.

Windows 95/98/Me: This parameter must be NULL. The AddPrinter function can only install local printers.

Level
[in] Specifies the version of the structure to which pPrinter points. This value must be 2.
pPrinter
[in] Pointer to a PRINTER_INFO_2 structure that contains information about the printer. You must specify non-NULL values for the pPrinterName, pPortName, pDriverName, and pPrintProcessor members of this structure before calling AddPrinter.

Return Values

If the function succeeds, the return value is the handle to a new printer object. When you are finished with the handle, pass it to the ClosePrinter function to close it.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The following are the members of the PRINTER_INFO_2 structure that can be set before the AddPrinter function is called:

Attributes
pPrintProcessor
DefaultPriority
Priority
pComment
pSecurityDescriptor
pDatatype 		pSepFile
pDevMode
pShareName
pLocation
StartTime
pParameters
UntilTime

The Status, cJobs, and AveragePPM members of the PRINTER_INFO_2 structure are reserved for use by the GetPrinter function. They must not be set before calling AddPrinter.

If pSecurityDescriptor is NULL, the system assigns a default security descriptor to the printer.

After an application creates a printer object with the AddPrinter function, it must use the PrinterProperties function to specify the correct settings for the printer driver associated with the printer object.

The AddPrinter function returns an error if a printer object with the same name already exists, unless that object is marked as pending deletion. In that case, the existing printer will not be deleted, and the AddPrinter creation parameters will be used to change the existing printer settings (as if the application had used the SetPrinter function).

Use the EnumPrintProcessors function to enumerate the set of print processors installed on a server. Use the EnumPrintProcessorDatatypes function to enumerate the set of data types that a print processor supports. Use the EnumPorts function to enumerate the set of available ports. Use the EnumPrinterDrivers function to enumerate the installed printer drivers.

Windows NT/Windows 2000 or later:The caller of the AddPrinter function must have SERVER_ACCESS_ADMINISTER access to the server on which the printer is to be created. The handle returned by the function will have PRINTER_ALL_ACCESS permission, and can be used to perform administrative operations on the printer.

Windows 95: Windows 95 does not support access validation or security on printer objects.

Whistler: If the DrvPrinterEvent function is passed the PRINTER_EVENT_FLAG_NO_UI flag, the driver should not use a UI call during DrvPrinterEvent. To do UI-related jobs, the installer should either use the VendorSetup entry in the printer's .inf file or, for Plug and Play devices, the installer can use a device-specific co-installer. For more information about VendorSetup, see the Microsoft Windows 2000 Driver Development Kit.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, ClosePrinter, DeletePrinter, EnumPorts, EnumPrinterDrivers, EnumPrintProcessors, EnumPrintProcessorDatatypes, GetPrinter, PRINTER_INFO_2, PrinterProperties, SetPrinter


AddPrinterConnection

The AddPrinterConnection function adds a connection to the specified printer for the current user.

BOOL AddPrinterConnection(
  LPTSTR pName   // printer name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of a printer to which the current user wishes to establish a connection.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When Windows NT makes a connection to a printer, it may need to copy printer driver files to the server to which the printer is attached. If the user does not have permission to copy files to the appropriate location, the AddPrinterConnection function fails, and GetLastError returns ERROR_ACCESS_DENIED.

A printer connection established by calling AddPrinterConnection will be enumerated when EnumPrinters is called with dwType set to PRINTER_ENUM_CONNECTION.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, ConnectToPrinterDlg, DeletePrinterConnection, EnumPrinters


AddPrinterDriver

The AddPrinterDriver function installs a local or remote printer driver and links the configuration, data, and driver files.

For more flexibility in installing or upgrading printer drivers, use the AddPrinterDriverEx function becaue it allows strict upgrade, strict downgrade, copying of newer files only, and copying of all files (regardless of the file time stamps).

BOOL AddPrinterDriver(
  LPTSTR pName,        // server name
  DWORD Level,         // driver information level
  LPBYTE pDriverInfo   // driver information buffer
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the driver should be installed.

If pName is NULL, the driver will be installed locally.

Windows 95/98/Me: This parameter must be NULL. The AddPrinterDriver function can only install local printer drivers.

Level
[in] Specifies the version of the structure to which pDriverInfo points.

This value can be 2, 3, 4, or 6.

pDriverInfo
[in] Pointer to a structure containing printer driver information This depends on the value of Level.
Value of Level | Printer driver structure
2 | DRIVER_INFO_2
3 | Windows 95, Windows NT 4.0 or later: DRIVER_INFO_3
4 | Windows 2000 or later: DRIVER_INFO_4
6 | Windows Me, Windows 2000 or later: DRIVER_INFO_6

If the pEnvironment member of the structure pointed to by pDriverInfo is NULL, the current environment of the caller/client (not of the destination/server) is used.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before an application calls the AddPrinterDriver function, all files required by the driver must be copied to the system's printer-driver directory. An application can retrieve the name of this directory by calling the GetPrinterDriverDirectory function.

An application can determine which printer drivers are currently installed by calling the EnumPrinterDrivers function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriverEx, DRIVER_INFO_2, DRIVER_INFO_3, DRIVER_INFO_4, DRIVER_INFO_6, EnumPrinterDrivers, GetPrinterDriverDirectory


AddPrinterDriverEx

The AddPrinterDriverEx function installs a local or remote printer driver and links the configuration, data, and driver files. Besides having the capabilities of AddPrinterDriver, it also has options that permit strict upgrade, strict downgrade, copying of newer files only, and copying of all files (regardless of file time stamps).

BOOL AddPrinterDriverEx(
  LPTSTR pName,          // server name
  DWORD Level,           // driver information level
  LPBYTE pDriverInfo,    // driver information buffer
  DWORD dwFileCopyFlags  // copy options
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the driver should be installed. If this parameter is NULL, the function installs the driver on the local computer.
Level
[in] Specifies the version of the structure to which pDriverInfo points. This value can be 2, 3, 4, or 6.
pDriverInfo
[in/out] Pointer to a structure containing printer driver information. It can be one of the following.
Value of Level | DRIVER_INFO_* structure
2 | DRIVER_INFO_2
3 | DRIVER_INFO_3
4 | DRIVER_INFO_4
6 | DRIVER_INFO_6

If the pEnvironment member of the structure pointed to by pDriverInfo is NULL, the function uses the current environment of the caller/client, not the environment of the destination/server.

dwFileCopyFlags
[in] Specifies options for copying the driver files. This parameter can be one of the following values.
Value | Meaning
APD_COPY_ALL_FILES | Add the printer driver and copy all the files in the printer-driver directory. The file time stamps are ignored with this option.
APD_COPY_FROM_DIRECTORY | Whistler: Add the printer driver using the fully qualified file names specified in the DRIVER_INFO_6 structure. This flag is ORed in conjunction with one of the other copy flags. If this flag is set, AddPrinterDriverEx will fail if the files do not exist where they are specified to exist by the DRIVER_INFO_6 structure. The files do not need to be copied to the system's printer-driver directory. See the Remarks.
APD_COPY_NEW_FILES | Add the printer driver and copy the files in the printer-driver directory that are newer than any corresponding files that are currently in use. This flag emulates the behavior of AddPrinterDriver.
APD_STRICT_DOWNGRADE | Add the printer driver only if all the files in the printer-driver directory are older than any corresponding files currently in use.
APD_STRICT_UPGRADE | Add the printer driver only if all the files in the printer-driver directory are newer than any corresponding files currently in use.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before calling the AddPrinterDriverEx function, all files required by the driver must be copied to the system's printer-driver directory. To retrieve the name of this directory, call the GetPrinterDriverDirectory function.

To determine which printer drivers are currently installed, call the EnumPrinterDrivers function.

If the printer driver has been successfully added, the function calls the DrvDriverEvent (DRIVER_EVENT_INITIALIZE, Level, DRIVER_INFO_*, lparam) function to allow the driver to perform any initializations required during the installation of a printer driver. For more information about DrvDriverEvent, see the Microsoft Windows 2000 Driver Development Kit.

Whistler: The driver should not use a UI call during the call to DrvDriverEvent. To do UI-related jobs, the installer should either use the VendorSetup entry in the printer's .inf file or, for Plug and Play devices, the installer can use a device-specific co-installer. For more information about VendorSetup, see the Microsoft Windows 2000 Driver Development Kit.

Whistler: The files that are referenced in the DRIVER_INFO_6 structure must be local to the machine from which the call is made. A file name can be a UNC name as long as the UNC name is the local machine.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriver, DRIVER_INFO_2, DRIVER_INFO_3, DRIVER_INFO_4, DRIVER_INFO_6, DeletePrinterDriverEx, EnumPrinterDrivers, GetPrinterDriverDirectory


AddPrintProcessor

The AddPrintProcessor function installs a print processor on the specified server and adds the print-processor name to an internal list of supported print processors.

BOOL AddPrintProcessor(
  LPTSTR pName,                // server name
  LPTSTR pEnvironment,         // environment name
  LPTSTR pPathName,            // path
  LPTSTR pPrintProcessorName   // print-processor name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the print processor should be installed. If this parameter is NULL, the print processor is installed locally.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the current environment of the caller/client (not of the destination/server) is used.
pPathName
[in] Pointer to a null-terminated string that specifies the name of the file that contains the print processor. This file must be in the system print-processor directory.
pPrintProcessorName
[in] Pointer to a null-terminated string that specifies the name of the print processor.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before calling the AddPrintProcessor function, an application should verify that the file containing the print processor is stored in the system print-processor directory. An application can retrieve the name of the system print-processor directory by calling the GetPrintProcessorDirectory function.

An application can determine the name of existing print processors by calling the EnumPrintProcessors function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EnumPrintProcessors, GetPrintProcessorDirectory


AddPrintProvidor

The AddPrintProvidor function installs a local print provider and links the configuration, data, and provider files.

BOOL AddPrintProvidor(
  LPTSTR pName,         // reserved, must be NULL
  DWORD Level,          // provider information level
  LPBYTE pProviderInfo  // provider information buffer
);

Parameters

pName
[in] Reserved; must be NULL.
Level
[in] Specifies the level of the structure to which pProviderInfo points. It can be one of the following.
Value | Meaning
1 | Function uses a PROVIDOR_INFO_1 structure.
2 | Windows 2000 or later: Function uses a PROVIDOR_INFO_2 structure.

pProviderInfo
[in] Pointer to a print provider structure, as indicated by Level.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before an application calls the AddPrintProvidor function, all files required by the provider must be copied to the SYSTEM32 directory.

A provider added by AddPrintProvidor may be removed by calling DeletePrintProvidor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrintProvidor, PROVIDOR_INFO_1, PROVIDOR_INFO_2


AdvancedDocumentProperties

The AdvancedDocumentProperties function displays a printer-configuration dialog box for the specified printer, allowing the user to configure that printer.

This function is a special case of the DocumentProperties function. For more details, see the Remarks sectioin.

LONG AdvancedDocumentProperties(
  HWND hWnd,               // handle to parent window
  HANDLE hPrinter,         // handle to printer object
  LPTSTR pDeviceName,      // driver name
  PDEVMODE pDevModeOutput, // modified device mode data
  PDEVMODE pDevModeInput   // original device mode data
);

Parameters

hWnd
[in] Handle to the parent window of the printer-configuration dialog box.
hPrinter
[in] Handle to a printer object. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pDeviceName
[in] Pointer to a null-terminated string specifying the name of the device for which a printer-configuration dialog box should be displayed.
pDevModeOutput
[out] Pointer to a DEVMODE structure that will contain the configuration data specified by the user.
pDevModeInput
[in] Pointer to a DEVMODE structure that contains the configuration data used to initialize the controls of the printer-configuration dialog box.

Return Values

If the DocumentProperties function with these parameters is successful, the return value of AdvancedDocumentProperties is 1. Otherwise, the return value is zero. To get extended error information, call GetLastError.

Remarks

This function can only display the printer-configuration dialog box so a user can configure it. For more control, use DocumentProperties. The input parameters for this function are passed directly to DocumentProperties and the fMode value is set to DM_IN_BUFFER | DM_IN_PROMPT | DM_OUT_BUFFER. Unlike DocumentProperties, this function only returns 1 or 0. Thus, you cannot determine the required size of DEVMODE by setting pDevMode to zero.

An application can obtain the name pointed to by the pDeviceName parameter by calling the GetPrinter function and then examining the pPrinterName member of the PRINTER_INFO_2 structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, DEVMODE, DocumentProperties, GetPrinter, OpenPrinter, PRINTER_INFO_2


ClosePrinter

The ClosePrinter function closes the specified printer object.

BOOL ClosePrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in] Handle to the printer object to be closed. This handle is returned by the OpenPrinter or AddPrinter function.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When the ClosePrinter function returns, the handle hPrinter is invalid, regardless of whether the function has succeeded or failed.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, OpenPrinter


ConfigurePort

The ConfigurePort function displays the port-configuration dialog box for a port on the specified server.

BOOL ConfigurePort(
  LPTSTR pName,      // server name
  HWND hWnd,         // handle to parent window
  LPTSTR pPortName   // port name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the specified port exists. If this parameter is NULL, the port is local.
hWnd
[in] Handle to the parent window of the port-configuration dialog box.
pPortName
[in] Pointer to a null-terminated string that specifies the name of the port to be configured.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before calling the ConfigurePort function, an application should call the EnumPorts function to determine valid port names.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EnumPorts


ConnectToPrinterDlg

The ConnectToPrinterDlg function displays a dialog box that lets users browse and connect to printers on a network. If the user selects a printer, the function attempts to create a connection to it; if a suitable driver is not installed on the server, the user is given the option of creating a printer locally.

HANDLE ConnectToPrinterDlg(
  HWND hwnd,    // handle to parent window
  DWORD Flags   // reserved; must be zero
);

Parameters

hwnd
[in] Specifies the parent window of the dialog box.
Flags
[in] This parameter is reserved and must be zero.

Return Values

If the function succeeds and the user selects a printer, the return value is a handle to the selected printer.

If the function fails, or the user cancels the dialog box without selecting a printer, the return value is NULL.

Remarks

The ConnectToPrinterDlg function attempts to create a connection to the selected printer. However, if the server on which the printer resides does not have a suitable driver installed, the function offers the user the option of creating a printer locally. A calling application can determine whether the function has created a printer locally by calling GetPrinter with a PRINTER_INFO_2 structure, then examining that structure's Attributes member.

An application should call DeletePrinter to delete a local printer. An application should call DeletePrinterConnection to delete a connection to a printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterConnection, ClosePrinter, DeletePrinter, DeletePrinterConnection, GetPrinter, PRINTER_INFO_2


DeleteForm

The DeleteForm function removes a form name from the list of supported forms.

BOOL DeleteForm(
  HANDLE hPrinter,  // handle to printer object
  LPTSTR pFormName  // form name
);

Parameters

hPrinter
[in] Indicates the open printer handle that this function is to be performed upon. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pFormName
[in] Pointer to the form name to be removed.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

DeleteForm can only delete form names that were added by using the AddForm function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddForm, OpenPrinter


DeleteMonitor

The DeleteMonitor function removes a port monitor added by the AddMonitor function.

BOOL DeleteMonitor(
  LPTSTR pName,         // server name
  LPTSTR pEnvironment,  // environment name
  LPTSTR pMonitorName   // monitor name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server from which the monitor is to be removed. If this parameter is NULL, the port monitor is removed locally.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment from which the monitor is to be removed (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the monitor is removed from the current environment of the calling application and client machine (not of the destination application and print server).
pMonitorName
[in] Pointer to a null-terminated string that specifies the name of the monitor to be removed.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddMonitor


DeletePort

The DeletePort function displays a dialog box that allows the user to delete a port name.

BOOL DeletePort(
  LPTSTR pName,      // server name
  HWND hWnd,         // handle to parent window
  LPTSTR pPortName   // port name
);

Parameters

pName
[in] Pointer to a zero-terminated string that specifies the name of the server for which the port should be deleted. If this parameter is NULL, a local port is deleted.
hWnd
[in] Handle to the parent window of the port-deletion dialog box.
pPortName
[in] Pointer to a zero-terminated string that specifies the name of the port that should be deleted.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

An application can retrieve the names of valid ports by calling the EnumPorts function.

The DeletePort function returns an error if a printer is currently connected to the specified port.

The caller of the DeletePort function must have SERVER_ACCESS_ADMINISTER access to the server to which the port is connected.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPort, EnumPorts


DeletePrinter

The DeletePrinter function deletes the specified printer object.

BOOL DeletePrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in/out] Handle to a printer object that will be deleted. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If there are print jobs remaining to be processed for the specified printer, DeletePrinter marks the printer for pending deletion, and then deletes it when all the print jobs have been printed. No print jobs can be added to a printer that is marked for pending deletion.

A printer marked for pending deletion cannot be held, but its print jobs can be held, resumed, and restarted. If the printer is held and there are jobs for the printer, DeletePrinter fails with an InvalidState error.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, EnumPrinters, OpenPrinter


DeletePrinterConnection

The DeletePrinterConnection function deletes a connection to a printer that was established by a call to AddPrinterConnection or ConnectToPrinterDlg.

BOOL DeletePrinterConnection(
  LPTSTR pName   // printer name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the printer connection to delete.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The DeletePrinterConnection function does not delete any printer driver files that were copied to the server to which the printer is attached.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterConnection, ConnectToPrinterDlg


DeletePrinterData

The DeletePrinterData function deletes specified configuration data for a printer. A printer's configuration data consists of a set of named and typed values. The DeletePrinterData function deletes one of these values, specified by its value name.

Windows 2000 or later: Calling DeletePrinterData is equivalent to calling the DeletePrinterDataEx function with the pKeyName parameter set to "PrinterDriverData".

DWORD DeletePrinterData(
  HANDLE hPrinter,   // handle to printer
  LPTSTR pValueName  // value name
);

Parameters

hPrinter
[in] Handle to the printer whose configuration data is to be deleted. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pValueName
[in] Pointer to the null-terminated name of the configuration data value to be deleted.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EnumPrinterData, GetPrinterData, OpenPrinter, SetPrinter, SetPrinterData


DeletePrinterDataEx

The DeletePrinterDataEx function deletes a specified value from the configuration data for a printer. A printer's configuration data consists of a set of named and typed values stored in a hierarchy of registry keys. The function deletes a specified value under a specified key.

Like the DeletePrinterData function, DeletePrinterDataEx can delete values stored by the SetPrinterData function. In addition, DeletePrinterDataEx can delete values stored under a specified key by the SetPrinterDataEx function.

DWORD DeletePrinterDataEx(
  HANDLE hPrinter,       // handle to printer object
  LPCTSTR pKeyName,      // registry key
  LPCTSTR pValueName     // value name
);

Parameters

hPrinter
[in] Handle to the printer for which the function deletes a value. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key containing the value to delete. Use the backslash ( \ ) character as a delimiter to specify a path that has one or more subkeys.

If pKeyName is NULL or an empty string, DeletePrinterDataEx returns ERROR_INVALID_PARAMETER.

pValueName
[in] Pointer to a null-terminated string that specifies the name of the value to delete.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterKey, EnumPrinterDataEx, EnumPrinterKey, GetPrinterDataEx, OpenPrinter, SetPrinterDataEx


DeletePrinterDriver

The DeletePrinterDriver function removes the specified printer-driver name from the list of names of supported drivers for a server.

To delete the files associated with the driver in addition to removing the specified printer-driver name from the list of names of supported drivers for a server, use the DeletePrinterDriverEx function.

DeletePrinterDriver deletes a driver only if no version of the driver is in use for the specified environment. DeletePrinterDriverEx can delete specific versions of the driver.

BOOL DeletePrinterDriver(
  LPTSTR pName,        // server name
  LPTSTR pEnvironment, // environment name
  LPTSTR pDriverName   // driver name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server from which the driver is to be deleted. If this parameter is NULL, the printer-driver name will be removed locally.

Windows 95/98/Me: This parameter must be NULL. The DeletePrinterDriver function can only delete local printer drivers.

pEnvironment
[in] Pointer to a null-terminated string that specifies the environment from which the driver is to be deleted (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the driver name is deleted from the current environment of the calling application and client machine (not of the destination application and print server).
pDriverName
[in] Pointer to a null-terminated string specifying the name of the driver that should be deleted.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The DeletePrinterDriver function does not delete the associated files, it merely removes the driver name from the list returned by the EnumPrinterDrivers function.

Before calling DeletePrinterDriver, you must delete all printer objects that use the printer driver.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterDriverEx, EnumPrinterDrivers


DeletePrinterDriverEx

The DeletePrinterDriverEx function removes the specified printer-driver name from the list of names of supported drivers for a server and deletes the files associated with the driver. This function can also delete specific versions of the driver.

BOOL DeletePrinterDriverEx(
  LPTSTR pName,         // server name
  LPTSTR pEnvironment,  // environment name
  LPTSTR pDriverName,   // driver name
  DWORD dwDeleteFlag,   // deletion options
  DWORD dwVersionFlag   // version number
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server from which the driver is to be deleted. If this parameter is NULL, the function deletes the printer-driver from the local computer.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment from which the driver is to be deleted (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the driver name is deleted from the current environment of the calling application and client computer (not of the destination application and print server).
pDriverName
[in] Pointer to a null-terminated string specifying the name of the driver to delete.
dwDeleteFlag
[in] Specifies options for deleting files and versions of the driver. This parameter can be one or more of the following values.
Value | Meaning
DPD_DELETE_SPECIFIC_VERSION | Deletes the version specified in dwVersionFlag. This does not ensure that the driver will be removed from the list of supported drivers for the server.
DPD_DELETE_UNUSED_FILES | Removes any unused driver files.
DPD_DELETE_ALL_FILES | Deletes the driver only if all its associated files can be removed. The delete operation fails if any of the driver's files are being used by some other installed driver.

If DPD_DELETE_SPECIFIC_VERSION is not specified, the function deletes all versions of the driver if none of them is in use. If neither DPD_DELETE_UNUSED_FILES nor DPD_DELETE_ALL_FILES is specified, the function does not delete driver files.

dwVersionFlag
[in] Specifies the version of the driver to be deleted. This parameter can be 0, 1, 2 or 3. This parameter is used only if dwDeleteFlag includes the DPD_DELETE_SPECIFIC_VERSION flag.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Before the function deletes the driver files, it calls the driver's DrvDriverEvent function, allowing the driver to remove any private files that are not used. For more information about DrvDriverEvent, see the Microsoft Windows 2000 Driver Development Kit.

If the driver files are currently loaded, the function moves them to a temp directory and marks them for deletion on restart.

Before calling DeletePrinterDriverEx, you must delete all printer objects that use the printer driver.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriverEx


DeletePrinterKey

The DeletePrinterKey function deletes a specified key and all its subkeys for a specified printer.

DWORD DeletePrinterKey(
  HANDLE hPrinter,     // handle to printer object
  LPCTSTR pKeyName     // registry key name
);

Parameters

hPrinter
[in] Handle to the printer for which the function deletes a key. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key to delete. Use the backslash ( \ ) character as a delimiter to specify a path with one or more subkeys.

If pKeyName is an empty string (""), DeletePrinterKey deletes all keys below the top-level key for the printer. If pKeyName is NULL, DeletePrinterKey returns ERROR_INVALID_PARAMETER.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterDataEx, EnumPrinterDataEx, EnumPrinterKey, GetPrinterDataEx, OpenPrinter, SetPrinterDataEx


DeletePrintProcessor

The DeletePrintProcessor function removes a printer processor added by the AddPrintProcessor function.

BOOL DeletePrintProcessor(
  LPTSTR pName,               // server name
  LPTSTR pEnvironment,        // environment name
  LPTSTR pPrintProcessorName  // processor name
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server from which the processor is to be removed. If this parameter is NULL, the printer processor is removed locally.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment from which the processor is to be removed (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the processor is removed from the current environment of the calling application and client machine (not of the destination application and print server). NULL is the recommended value, as it provides maximum portability.
pPrintProcessorName
[in] Pointer to a null-terminated string that specifies the name of the processor to be removed.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrintProcessor


DeletePrintProvidor

The DeletePrintProvidor function removes a local print provider added by the AddPrintProvidor function.

BOOL DeletePrintProvidor(
  LPTSTR pName,               // reserved, must be NULL
  LPTSTR pEnvironment,        // environment name
  LPTSTR pPrintProviderName   // provider name
);

Parameters

pName
[in] Reserved; must be NULL.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment from which the provider is to be removed (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0). If this parameter is NULL, the provider is removed from the current environment of the calling application and client machine (not of the destination application and print server). NULL is the recommended value because it provides maximum portability.
pPrintProviderName
[in] Pointer to a null-terminated string that specifies the name of the provider to be removed.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrintProvidor


DeviceCapabilities

The DeviceCapabilities function retrieves the capabilities of a printer device driver.

DWORD DeviceCapabilities(
  LPCTSTR pDevice,         // printer name
  LPCTSTR pPort,           // port name
  WORD fwCapability,       // device capability
  LPTSTR pOutput,          // output buffer
  CONST DEVMODE *pDevMode  // device data buffer
);

Parameters

pDevice
[in] Pointer to a null-terminated string that contains the name of the printer. Note that this is the name of the printer, not of the printer driver.
pPort
[in] Pointer to a null-terminated string that contains the name of the port to which the device is connected, such as LPT1.
fwCapability
[in] Specifies the capabilities to query. This parameter can be one of the following values.
Value | Meaning
DC_BINADJUST Windows 95/98/Me: Retrieves the page positioning for the paper source specified in the DEVMODE structure pointed to by pdevMode. The return value can be one of the following:

DCBA_FACEUPNONE
DCBA_FACEUPCENTER
DCBA_FACEUPLEFT
DCBA_FACEUPRIGHT
DCBA_FACEDOWNNONE
DCBA_FACEDOWNCENTER
DCBA_FACEDOWNLEFT
DCBA_FACEDOWNRIGHT

Windows NT/2000 or later: Not supported.
DC_BINNAMES | Retrieves the names of the printer's paper bins. The pOutput buffer receives an array of string buffers. Each string buffer is 24 characters long and contains the name of a paper bin. The return value indicates the number of entries in the array. The name strings are null-terminated unless the name is 24 characters long. If pOutput is NULL, the return value is the number of bin entries required.
DC_BINS | Retrieves a list of available paper bins. The pOutput buffer receives an array of WORD values that indicate the available paper sources for the printer. The return value indicates the number of entries in the array. For a list of the possible array values, see the description of the dmDefaultSource member of the DEVMODE structure. If pOutput is NULL, the return value indicates the required number of entries in the array.
DC_COLLATE | If the printer supports collating, the return value is 1; otherwise, the return value is zero. The pOutput parameter is not used.
DC_COLORDEVICE | Windows 2000 or later: If the printer supports color printing, the return value is 1; otherwise, the return value is zero. The pOutput parameter is not used.
DC_COPIES | Returns the number of copies the device can print.
DC_DRIVER | Returns the version number of the printer driver.
DC_DATATYPE_PRODUCED Windows 95/98/Me: The return value is the number of datatypes supported by the printer driver. If the function returns -1, the driver recognizes only the"RAW" datatype. The names of the supported datatypes are copied to an array. Use the names in the DOCINFO structure when calling the StartDoc function to specify the datatype.

Windows NT/2000 or later: Not supported.
DC_DUPLEX | If the printer supports duplex printing, the return value is 1; otherwise, the return value is zero. The pOutput parameter is not used.
DC_EMF_COMPLIANT Windows 95/98/Me: Determines if a printer driver supports enhanced metafiles (EMF). A return value of 1 means the driver supports EMF. A return value of -1 means the driver does not support EMF.

Windows NT/2000 or later: Not supported.
DC_ENUMRESOLUTIONS | Retrieves a list of the resolutions supported by the printer. The pOutput buffer receives an array of LONG values. For each supported resolution, the array contains a pair of LONG values that specify the x and y dimensions of the resolution, in dots per inch. The return value indicates the number of supported resolutions. If pOutput is NULL, the return value indicates the number of supported resolutions.
DC_EXTRA | Returns the number of bytes required for the device-specific portion of the DEVMODE structure for the printer driver.
DC_FIELDS | Returns the dmFields member of the printer driver's DEVMODE structure. The dmFields member indicates which members in the device-independent portion of the structure are supported by the printer driver.
DC_FILEDEPENDENCIES | Retrieves the names of any additional files that need to be loaded when a driver is installed. The pOutput buffer receives an array of string buffers. Each string buffer is 64 characters long and contains the name of a file. The return value indicates the number of entries in the array. The name strings are null-terminated unless the name is 64 characters long. If pOutput is NULL, the return value is the number of files.
DC_MANUFACTURER Windows 95/98/Me: The return value is the identification number of the printer manufacturer. This value is used with Image Color Management (ICM).

Windows NT/2000 or later: Not supported.
DC_MAXEXTENT | Returns the maximum paper size that the dmPaperLength and dmPaperWidth members of the printer driver's DEVMODE structure can specify. The LOWORD of the return value contains the maximum dmPaperWidth value, and the HIWORD contains the maximum dmPaperLength value.
DC_MEDIAREADY | Windows 2000 or later: Retrieves the names of the paper forms that are currently available for use. The pOutput buffer receives an array of string buffers. Each string buffer is 64 characters long and contains the name of a paper form. The return value indicates the number of entries in the array. The name strings are null-terminated unless the name is 64 characters long. If pOutput is NULL, the return value is the number of paper forms.
DC_MEDIATYPENAMES | Whistler: Retrieves the names of the supported media types. The pOutput buffer receives an array of string buffers. Each string buffer is 64 characters long and contains the name of a supported media type. The return value indicates the number of entries in the array. The strings are null-terminated unless the name is 64 characters long. If pOutput is NULL, the return value is the number of media type names required.
DC_MEDIATYPES | Whistler: Retrieves a list of supported media types. The pOutput buffer receives an array of DWORD values that indicate the supported media types. The return value indicates the number of entries in the array. For a list of possible array values, see the description of the dmMediaType member of the DEVMODE structure. If pOutput is NULL, the return value indicates the required number of entries in the array.
DC_MINEXTENT | Returns the minimum paper size that the dmPaperLength and dmPaperWidth members of the printer driver's DEVMODE structure can specify. The LOWORD of the return value contains the minimum dmPaperWidth value, and the HIWORD contains the minimum dmPaperLength value.
DC_MODEL Windows 95/98/Me: The return value is the identification of the printer model. This value is used with Image Color Management (ICM).

Windows NT/2000 or later: Not supported.
DC_ORIENTATION Returns the relationship between portrait and landscape orientations for a device, in terms of the number of degrees that portrait orientation is rotated counterclockwise to produce landscape orientation. The return value can be one of the following:
0
No landscape orientation.
90
Portrait is rotated 90 degresss to produce landscape.
270
Portrait is rotated 270 degrees to produce landscape.
DC_NUP | Windows 2000 or later: Retrieves an array of integers that indicate that printer's ability to print multiple document pages per printed page. The pOutput buffer receives an array of DWORD values. Each value represents a supported number of document pages per printed page. The return value indicates the number of entries in the array. If pOutput is NULL, the return value indicates the required number of entries in the array.
DC_PAPERNAMES | Retrieves a list of supported paper names (for example, Letter or Legal). The pOutput buffer receives an array of string buffers. Each string buffer is 64 characters long and contains the name of a paper form. The return value indicates the number of entries in the array. The name strings are null-terminated unless the name is 64 characters long. If pOutput is NULL, the return value is the number of paper forms.
DC_PAPERS | Retrieves a list of supported paper sizes. The pOutput buffer receives an array of WORD values that indicate the available paper sizes for the printer. The return value indicates the number of entries in the array. For a list of the possible array values, see the description of the dmPaperSize member of the DEVMODE structure. If pOutput is NULL, the return value indicates the required number of entries in the array.
DC_PAPERSIZE | Retrieves the dimensions, in tenths of a millimeter, of each supported paper size. The pOutput buffer receives an array of POINT structures. Each structure contains the width (x-dimension) and length (y-dimension) of a paper size as if the paper were in the DMORIENT_PORTRAIT orientation. The return value indicates the number of entries in the array.
DC_PERSONALITY | Windows 2000 or later: Retrieves a list of printer description languages supported by the printer. The pOutput buffer receives an array of string buffers. Each buffer is 32 characters long and contains the name of a printer description language. The return value indicates the number of entries in the array. The name strings are null-terminated unless the name is 32 characters long. If pOutput is NULL, the return value indicates the required number of array entries.
DC_PRINTERMEM | Windows 2000 or later: The return value is the amount of available printer memory, in kilobytes. The pOutput parameter is not used.
DC_PRINTRATE | Windows 2000 or later: The return value indicates the printer's print rate. The value returned for DC_PRINTRATEUNIT indicates the units of the DC_PRINTRATE value. The pOutput parameter is not used.
DC_PRINTRATEPPM | Windows 2000 or later: The return value indicates the printer's print rate, in pages per minute. The pOutput parameter is not used.
DC_PRINTRATEUNIT Windows 2000 or later: The return value is one of the following values that indicate the print rate units for the value returned for the DC_PRINTRATE flag. The pOutput parameter is not used.
PRINTRATEUNIT_CPS
Characters per second.
PRINTRATEUNIT_IPM
Inches per minute.
PRINTRATEUNIT_LPM
Lines per minute.
PRINTRATEUNIT_PPM
Pages per minute.
DC_SIZE | Returns the dmSize member of the printer driver's DEVMODE structure.
DC_STAPLE | Windows 2000 or later: If the printer supports stapling, the return value is a nonzero value; otherwise, the return value is zero. The pOutput parameter is not used.
DC_TRUETYPE Retrieves the abilities of the driver to use TrueType fonts. For DC_TRUETYPE, the pOutput parameter should be NULL. The return value can be one or more of the following:
DCTT_BITMAP
Device can print TrueType fonts as graphics.
DCTT_DOWNLOAD
Device can down-load TrueType fonts.
DCTT_DOWNLOAD_OUTLINE
Windows 95/98/Me: Device can download outline TrueType fonts.
DCTT_SUBDEV
Device can substitute device fonts for TrueType fonts.
DC_VERSION | Returns the specification version to which the printer driver conforms.

pOutput
[out] Pointer to an array. The format of the array depends on the setting of the fwCapability parameter. If pOutput is NULL, DeviceCapabilities returns the number of bytes required for the output data.
pDevMode
[in] Pointer to a DEVMODE structure. If this parameter is NULL, DeviceCapabilities retrieves the current default initialization values for the specified printer driver. Otherwise, the function retrieves the values contained in the structure to which pDevMode points.

Return Values

If the function succeeds, the return value depends on the setting of the fwCapability parameter. A return value of zero generally indicates that, while the function completed successfully, there was some type of failure, such as a capability that is not supported. For more details, see the descriptions for the fwCapability values.

If the function fails, the return value is -1.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

For 16-bit programs, DeviceCapabilities was implemented in the printer driver. To get a pointer to the function, call LoadLibrary and GetProcAddress. For 32-bit applications on both Windows 95/98 and Windows NT, DeviceCapabilities is part of the Win32 API, so you should not call LoadLibrary on the printer driver.

The DEVMODE structure pointed to by the pDevMode parameter may be obtained by calling the DocumentProperties function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DEVMODE, DOCINFO, DocumentProperties, GetDeviceCaps, GetProcAddress, LoadLibrary, POINT, StartDoc


DocumentProperties

The DocumentProperties function retrieves or modifies printer initialization information or displays a printer-configuration property sheet for the specified printer.

Windows 95/98/Me: The DocumentProperties and PrinterProperties functions both display the same property sheet, which includes pages for setting document properties and printer properties.

LONG DocumentProperties(
  HWND hWnd,               // handle to parent window
  HANDLE hPrinter,         // handle to printer object
  LPTSTR pDeviceName,      // device name
  PDEVMODE pDevModeOutput, // modified device mode
  PDEVMODE pDevModeInput,  // original device mode
  DWORD fMode              // mode options
);

Parameters

hWnd
[in] Handle to the parent window of the printer-configuration property sheet.
hPrinter
[in] Handle to a printer object. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pDeviceName
[in] Pointer to a null-terminated string that specifies the name of the device for which the printer-configuration property sheet is displayed.
pDevModeOutput
[out] Pointer to a DEVMODE structure that receives the printer configuration data specified by the user.
pDevModeInput
[in] Pointer to a DEVMODE structure that the operating system uses to initialize the property sheetcontrols.

This parameter is only used if the DM_IN_BUFFER flag is set in the fMode parameter. If DM_IN_BUFFER is not set, the operating system uses the printer's default DEVMODE.

fMode
[in] Specifies the operations the function performs. If this parameter is zero, the DocumentProperties function returns the number of bytes required by the printer driver's DEVMODE data structure. Otherwise, use one or more of the following constants to construct a value for this parameter; note, however, that in order to change the print settings, an application must specify at least one input value and one output value.
Value | Meaning
DM_IN_BUFFER | Input value. Before prompting, copying, or updating, the function merges the printer driver's current print settings with the settings in the DEVMODE structure specified by the pDevModeInput parameter. The function updates the structure only for those members specified by the DEVMODE structure's dmFields member. This value is also defined as DM_MODIFY. In cases of conflict during the merge, the settings in the DEVMODE structure specified by pDevModeInput override the printer driver's current print settings.
DM_IN_PROMPT | Input value. The function presents the printer driver's Print Setup property sheet and then changes the settings in the printer's DEVMODE data structure to those values specified by the user. This value is also defined as DM_PROMPT.
DM_OUT_BUFFER | Output value. The function writes the printer driver's current print settings, including private data, to the DEVMODE data structure specified by the pDevModeOutput parameter. The caller must allocate a buffer sufficiently large to contain the information. If the bit DM_OUT_BUFFER sets is clear, the pDevModeOutput parameter can be NULL. This value is also defined as DM_COPY.

Return Values

If the fMode parameter is zero, the return value is the size of the buffer required to contain the printer driver initialization data. Note that this buffer can be larger than a DEVMODE structure if the printer driver appends private data to the structure.

If the function displays the property sheet, the return value is either IDOK or IDCANCEL, depending on which button the user selects.

If the function does not display the property sheet and is successful, the return value is IDOK.

If the function fails, the return value is less than zero. To get extended error information, call GetLastError.

Remarks

The string pointed to by the pDeviceName parameter can be obtained by calling the GetPrinter function.

Note The DEVMODE structure actually used by a printer driver contains the device-independent part (as defined above) followed by a driver-specific part that varies in size and content with each driver and driver version. Because of this driver dependence, it is very important for applications to query the driver for the correct size of the DEVMODE structure before allocating a buffer for it.

To make changes to print settings that are local to an application, an application should follow these steps:

  1. Get the number of bytes required for the full DEVMODE structure by calling DocumentProperties and specifying zero in the fMode parameter.
  2. Allocate memory for the full DEVMODE structure.
  3. Get the current printer settings by calling DocumentProperties. Pass a pointer to the DEVMODE structure allocated in Step 2 as the pDevModeOutput parameter and specify the DM_OUT_BUFFER value.
  4. Modify the appropriate members of the returned DEVMODE structure and indicate which members were changed by setting the corresponding bits in the dmFields member of the DEVMODE.
  5. Call DocumentProperties and pass the modified DEVMODE structure back as both the pDevModeInput and pDevModeOutput parameters and specify both the DM_IN_BUFFER and DM_OUT_BUFFER values (which are combined using the OR operator).

The DEVMODE structure returned by the third call to DocumentProperties can be used as an argument in a call to the CreateDC function.

To create a handle to a printer-device context using the current printer settings, you only need to call DocumentProperties twice, as described above. The first call gets the size of the full DEVMODE and the second call initializes the DEVMODE with the current printer settings. Pass the initialized DEVMODE to CreateDC to obtain the handle to the printer device context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AdvancedDocumentProperties, CreateDC, DEVMODE, GetPrinter, OpenPrinter


EndDoc

The EndDoc function ends a print job.

int EndDoc(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context for the print job.

Return Values

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

Applications should call EndDoc immediately after finishing a print job.

For an example, see Printing a Document.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, StartDoc


EndDocPrinter

The EndDocPrinter function ends a print job for the specified printer.

BOOL EndDocPrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in] Handle to a printer for which the print job should be ended. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EndDocPrinter function returns an error if the print job was not started by calling the StartDocPrinter function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, StartDocPrinter


EndPage

The EndPage function notifies the device that the application has finished writing to a page. This function is typically used to direct the device driver to advance to a new page.

int EndPage(
  HDC hdc   // handle to DC
);

Parameters

hdc
[in] Handle to the device context for the print job.

Return Values

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

Use the ResetDC function to change the device mode, if necessary, after calling the EndPage function. Note that a call to ResetDC resets all device context attributes back to default values:

  • Windows 3.x: EndPage resets the device context attributes back to default values. You must re-select objects and set up the mapping mode again before printing the next page.
  • Windows 95: EndPage does not reset the device context attributes. However, the next StartPage call does reset the device context attributes to default values. At that time, you must re-select objects and set up the mapping mode again before printing the next page.
  • Windows NT/Windows 2000 or later: Beginning with Windows NT Version 3.5, neither EndPage or StartPage resets the device context attributes. Device context attributes remain constant across subsequent pages. You do not need to re-select objects and set up the mapping mode again before printing the next page; however, doing so will produce the same results and reduce code differences between Windows 95 and Windows NT.

Windows 2000: When a page in a spooled file exceeds approximately 350 MB, it may fail to print and not send an error message. For example, this can occur when printing large EMF files. The page size limit depends on many factors including the amount of virtual memory available, the amount of memory allocated by calling processes, and the amount of fragmentation in the process heap.

For an example, see Printing a Document.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, ResetDC, StartPage


EndPagePrinter

The EndPagePrinter function notifies the print spooler that the application is at the end of a page in a print job.

BOOL EndPagePrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in] Handle to the printer for which the page will be concluded. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Each page in a print job begins with a StartPagePrinter function call and ends with an EndPagePrinter function call. The data for each page is written to the print file by using the WritePrinter function.

Windows 2000: When a page in a spooled file exceeds approximately 350 MB, it may fail to print and not send an error message. For example, this can occur when printing large EMF files. The page size limit depends on many factors including the amount of virtual memory available, the amount of memory allocated by calling processes, and the amount of fragmentation in the process heap.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter, StartPagePrinter, WritePrinter


EnumForms

The EnumForms function enumerates the forms supported by the specified printer.

BOOL EnumForms(
  HANDLE hPrinter,    // handle to printer object
  DWORD Level,        // data level
  LPBYTE pForm,       // form information buffer
  DWORD cbBuf,        // size of form information buffer
  LPDWORD pcbNeeded,  // bytes received or required
  LPDWORD pcReturned  // number of forms received
);

Parameters

hPrinter
[in] Handle to the printer for which the forms should be enumerated. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the version of the structure to which pForm points. This value must be 1.
pForm
[out] Pointer to a FORM_INFO_1 structure.
cbBuf
[in] Specifies the size, in bytes, of the buffer to which pForm points.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied to or the number of bytes required for the array to which pForm points. If cbBuf is too small, this value specifies the number of bytes required; otherwise, this value specifies the number of bytes copied.
pcReturned
[out] Pointer to a variable that receives the number of FORM_INFO_1 structures copied into the array to which pForm points.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, FORM_INFO_1, OpenPrinter


EnumJobs

The EnumJobs function retrieves information about a specified set of print jobs for a specified printer.

BOOL EnumJobs(
  HANDLE hPrinter,    // handle to printer object
  DWORD FirstJob,     // index of first job
  DWORD NoJobs,       // number of jobs to enumerate
  DWORD Level,        // information level
  LPBYTE pJob,        // job information buffer
  DWORD cbBuf,        // size of job information buffer
  LPDWORD pcbNeeded,  // bytes received or required
  LPDWORD pcReturned  // number of jobs received
);

Parameters

hPrinter
[in] Handle to the printer object whose print jobs the function enumerates. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
FirstJob
[in] Specifies the zero-based position within the print queue of the first print job to enumerate. For example, a value of 0 specifies that enumeration should begin at the first print job in the print queue; a value of 9 specifies that enumeration should begin at the tenth print job in the print queue.
NoJobs
[in] Specifies the total number of print jobs to enumerate.
Level
[in] Specifies the type of information returned in the pJob buffer. If Level is 1, pJob receives an array of JOB_INFO_1 structures. If Level is 2, pJob receives an array of JOB_INFO_2 structures.
pJob
[out] Pointer to a buffer that receives an array of JOB_INFO_1 or JOB_INFO_2 structures. The buffer must be large enough to receive the array of structures and any strings or other data to which the structure members point.

To determine the required buffer size, call EnumJobs with cbBuf set to zero. EnumJobs fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the pJob buffer.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied if the function succeeds. If the function fails, the variable receives the number of bytes required.
pcReturned
[out] Pointer to a variable that receives the number of JOB_INFO_1 or JOB_INFO_2 structures returned in the pJob buffer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The JOB_INFO_1 structure contains general print-job information; the JOB_INFO_2 structure has much more detailed information.

To determine the number of print jobs in the printer queue, call the GetPrinter function with the Level parameter set to 2.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetJob, GetPrinter, JOB_INFO_1, JOB_INFO_2, OpenPrinter, SetJob


EnumMonitors

The EnumMonitors function retrieves information about the port monitors installed on the specified server.

BOOL EnumMonitors(
  LPTSTR pName,       // server name
  DWORD Level,        // information level
  LPBYTE pMonitors,   // monitor information buffer
  DWORD cbBuf,        // size of monitor information buffer
  LPDWORD pcbNeeded,  // bytes received or required
  LPDWORD pcReturned  // number of monitors received
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the monitors reside. If this parameter is NULL, the local monitors are enumerated.
Level
[in] Specifies the version of the structure pointed to by pMonitors.

Windows NT/Windows 2000 or later: This value can be 1 or 2.

Windows 95/98/Me: This value must be 1.

pMonitors
[out] Pointer to a buffer that receives an array of structures. The buffer must be large enough to store the strings referenced by the structure members.

To determine the required buffer size, call EnumMonitors with cbBuf set to zero. EnumMonitors fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

Windows NT/Windows 2000 or later: The buffer receives an array of MONITOR_INFO_1 structures if Level is 1, or MONITOR_INFO_2 structures if Level is 2.

Windows 95/98/Me: The buffer receives an array of MONITOR_INFO_1 structures if Level is 1.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pMonitors.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.
pcReturned
[out] Pointer to a variable that receives the number of structures that were returned in the buffer pointed to by pMonitors.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, MONITOR_INFO_1, MONITOR_INFO_2


EnumPorts

The EnumPorts function enumerates the ports that are available for printing on a specified server.

BOOL EnumPorts(
  LPTSTR pName,       // server name
  DWORD Level,        // information level
  LPBYTE pPorts,      // port information buffer
  DWORD cbBuf,        // size of port information buffer
  LPDWORD pcbNeeded,  // bytes received or required
  LPDWORD pcReturned  // number of ports received
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server whose printer ports you wish to enumerate.

If pName is NULL, the function enumerates the local machine's printer ports.

Level
[in] Specifies the type of information returned in the pPorts buffer. If Level is 1, pPorts receives an array of PORT_INFO_1 structures. If Level is 2, pPorts receives an array of PORT_INFO_2 structures.
pPorts
[out] Pointer to a buffer that receives an array of PORT_INFO_1 or PORT_INFO_2 structures. Each structure contains data that describes an available printer port. The buffer must be large enough to store the strings pointed to by the structure members.

To determine the required buffer size, call EnumPorts with cbBuf set to zero. EnumPorts fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pPorts.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied to the pPorts buffer. If the the buffer is too small, the function fails and the variable receives the number of bytes required.
pcReturned
[out] Pointer to a variable that receives the number of PORT_INFO_1 or PORT_INFO_2 structures returned in the pPorts buffer. This is the number of printer ports that are available on the specified server.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The EnumPorts function can succeed even if the server specified by pName does not have a printer defined.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPort, DeletePort, PORT_INFO_1, PORT_INFO_2


EnumPrinterData

The EnumPrinterData function enumerates configuration data for a specified printer.

To retrieve the configuration data in a single call, use the EnumPrinterDataEx function.

DWORD EnumPrinterData(
  HANDLE hPrinter,       // handle to printer
  DWORD dwIndex,         // index of value to retrieve
  LPTSTR pValueName,     // value name buffer
  DWORD cbValueName,     // size of value name buffer
  LPDWORD pcbValueName,  // bytes received
  LPDWORD pType,         // value type code
  LPBYTE pData,          // value data buffer
  DWORD cbData,          // size of value data buffer
  LPDWORD pcbData        // bytes received
);

Parameters

hPrinter
[in] Handle to the printer whose configuration data is to be obtained. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
dwIndex
[in] An index value that specifies the configuration data value to retrieve.

Set this parameter to zero for the first call to EnumPrinterData for a specified printer handle. Then increment the parameter by one for subsequent calls involving the same printer, until the function returns ERROR_NO_MORE_ITEMS. See the following Remarks section for further information.

If you use the technique mentioned in the descriptions of the cbValueName and cbData parameters to obtain adequate buffer size values, setting both those parameters to zero in a first call to EnumPrinterData for a specified printer handle, the value of dwIndex does not matter for that call. Set dwIndex to zero in the next call to EnumPrinterData to start the actual enumeration process.

Configuration data values are not ordered. New values will have an arbitrary index. This means that the EnumPrinterData function may return values in any order.

pValueName
[out] Pointer to a buffer that receives the name of the configuration data value, including a terminating null character.
cbValueName
[in] Specifies the size, in bytes, of the buffer pointed to by pValueName.

If you want to have the operating system supply an adequate buffer size, set both this parameter and the cbData parameter to zero for the first call to EnumPrinterData for a specified printer handle. When the function returns, the variable pointed to by pcbValueName will contain a buffer size that is large enough to successfully enumerate all of the printer's configuration data value names.

pcbValueName
[out] Pointer to a variable that receives the number of bytes stored into the buffer pointed to by pValueName.
pType
[out] Pointer to a variable that receives a code indicating the type of data stored in the specified value. For a list of the possible type codes, see Registry Value Types. The pType parameter can be NULL if the type code is not required.
pData
[out] Pointer to a buffer that receives the configuration data value.

This parameter can be NULL if the configuration data value is not required.

cbData
[in] Specifies the size, in bytes, of the buffer pointed to by pData.

If you want to have the operating system supply an adequate buffer size, set both this parameter and the cbValueName parameter to zero for the first call to EnumPrinterData for a specified printer handle. When the function returns, the variable pointed to by pcbData will contain a buffer size that is large enough to successfully enumerate all of the printer's configuration data value names.

pcbData
[out] Pointer to a variable that receives the number of bytes stored into the buffer pointed to by pData.

This parameter can be NULL if pData is NULL.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value.

The function returns ERROR_NO_MORE_ITEMS when there are no more configuration data values to retrieve for a specified printer handle.

Remarks

EnumPrinterData retrieves printer configuration data set by the SetPrinterData function. A printer's configuration data consists of a set of named and typed values. The EnumPrinterData function obtains one of these values, and its name and a type code, each time you call it. Call the EnumPrinterData function several times in succession to obtain all of a printer's configuration data values.

Printer configuration data is stored in the registry. While enumerating printer configuration data, you should avoid calling registry functions that might change that data.

If you want to have the operating system supply an adequate buffer size, first call EnumPrinterData with both the cbValueName and cbData parameters set to zero, as noted earlier in the Parameters section. The value of dwIndex does not matter for this call. When the function returns, *pcbValueName and *pcbData will contain buffer sizes that are large enough to enumerate all of the printer's configuration data value names and values. On the next call, allocate value name and data buffers, set cbValueName and cbData to the sizes in bytes of the allocated buffers, and set dwIndex to zero. Thereafter, continue to call the EnumPrinterData function, incrementing dwIndex by one each time, until the function returns ERROR_NO_MORE_ITEMS.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterData, EnumPrinterDataEx, GetPrinterData, OpenPrinter, SetPrinter, SetPrinterData


EnumPrinterDataEx

The EnumPrinterDataEx function enumerates all value names and data for a specified printer and key.

Printer data is stored in the registry. While enumerating printer data, do not call registry functions that might change the data.

DWORD EnumPrinterDataEx(
  HANDLE hPrinter,       // handle to printer object
  LPCTSTR pKeyName,      // registry key name
  LPBYTE pEnumValues,    // array of values
  DWORD cbEnumValues,    // size of values array
  LPDWORD pcbEnumValues, // bytes in the values array
  LPDWORD pnEnumValues   // number of values enumerated
);

Parameters

hPrinter
[in] Handle to the printer for which the function retrieves configuration data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key containing the values to enumerate. Use the backslash ( \ ) character as a delimiter to specify a path with one or more subkeys. EnumPrinterDataEx enumerates all values of the key, but does not enumerate values of subkeys of the specified key. Use the EnumPrinterKey function to enumerate subkeys.

If pKeyName is NULL or an empty string, EnumPrinterDataEx returns ERROR_INVALID_PARAMETER.

pEnumValues
[out] Pointer to a buffer that receives an array of PRINTER_ENUM_VALUES structures. Each structure contains the value name, type, data, and sizes of a value under the key.
cbEnumValues
[in] Specifies the size, in bytes, of the buffer pointed to by pcbEnumValues. If you set cbEnumValues to zero, the pcbEnumValues parameter returns the required buffer size.
pcbEnumValues
[out] Pointer to a variable that receives the size, in bytes, of the retrieved configuration data. If the buffer size specified by cbEnumValues is too small, the function returns ERROR_MORE_DATA and pcbEnumValues indicates the required buffer size.
pnEnumValues
[out] Pointer to a variable that receives the number of PRINTER_ENUM_VALUES structures returned in pEnumValues.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value.

Remarks

EnumPrinterDataEx retrieves printer configuration data set by the SetPrinterDataEx and SetPrinterData functions.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterDataEx, EnumPrinterKey, GetPrinterDataEx, OpenPrinter, PRINTER_ENUM_VALUES, SetPrinterData, SetPrinterDataEx


EnumPrinterDrivers

The EnumPrinterDrivers function enumerates the printer drivers installed on a specified printer server.

BOOL EnumPrinterDrivers(
  LPTSTR pName,        // printer server name
  LPTSTR pEnvironment, // environment name
  DWORD Level,         // information level
  LPBYTE pDriverInfo,  // driver information buffer
  DWORD cbBuf,         // size of driver information buffer
  LPDWORD pcbNeeded,   // bytes received or required
  LPDWORD pcReturned   // number of drivers received
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the printer drivers are enumerated.

If pName is NULL, the function enumerates the local printer drivers.

pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the function uses the current environment of the caller/client (not of the destination/server).

Windows 2000 or later: If the pEnvironment string specifies "all", EnumPrinterDrivers enumerates printer drivers for all platforms installed on the specified server.

Level
[in] Specifies the type of information structure returned in the pDriverInfo buffer. It can be one of the following.
Level | Structure
1 | DRIVER_INFO_1
2 | DRIVER_INFO_2
3 | Windows 95, Windows NT4.0 or later: DRIVER_INFO_3
4 | Windows 2000 or later: DRIVER_INFO_4
5 | Windows 2000 or later: DRIVER_INFO_5
6 | Windows Me, Windows 2000 or later: DRIVER_INFO_6

pDriverInfo
[in] Pointer to a buffer that receives an array of DRIVER_INFO_* structures, as specified by Level. Each structure contains data that describes an available printer driver. The buffer must be large enough to receive the array of structures and any strings or other data to which the structure members point.

To determine the required buffer size, call EnumPrinterDrivers with cbBuf set to zero. EnumPrinterDrivers fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pDriverInfo.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied to the pDriverInfo buffer if the function succeeds. If the buffer is too small, the function fails and the variable receives the number of bytes required.
pcReturned
[out] Pointer to a variable that receives the number of structures returned in the pDriverInfo buffer. This is the number of printer drivers installed on the specified print server.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriver, DRIVER_INFO_1, DRIVER_INFO_2, DRIVER_INFO_3, DRIVER_INFO_4, DRIVER_INFO_5, DRIVER_INFO_6, GetPrinterDriver


EnumPrinterKey

The EnumPrinterKey function enumerates the subkeys of a specified key for a specified printer.

Printer data is stored in the registry. While enumerating printer data, do not call registry functions that might change the data.

DWORD EnumPrinterKey(
  HANDLE hPrinter,  // handle to printer object
  LPCTSTR pKeyName, // registry key name
  LPTSTR pSubkey,   // array of subkey names
  DWORD cbSubkey,   // size subkey array
  LPDWORD pcbSubkey // bytes received in subkey array
);

Parameters

hPrinter
[in] Handle to the printer for which the function enumerates subkeys. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key containing the subkeys to enumerate. Use the backslash '\' character as a delimiter to specify a path with one or more subkeys. EnumPrinterKey enumerates all subkeys of the key, but does not enumerate the subkeys of those subkeys.

If pKeyName is an empty string (""), EnumPrinterKey enumerates the top-level key for the printer. If pKeyName is NULL, EnumPrinterKey returns ERROR_INVALID_PARAMETER.

pSubkey
[out] Pointer to a buffer that receives an array of null-terminated subkey names. The array is terminated by two null characters.
cbSubkey
[in] Specifies the size, in bytes, of the buffer pointed to by pSubkey. If you set cbSubkey to zero, the pcbSubkey parameter returns the required buffer size.
pcbSubkey
[out] Pointer to a variable that receives the number of bytes retrieved in the pSubkey buffer. If the buffer size specified by cbSubkey is too small, the function returns ERROR_MORE_DATA and pcbSubkey indicates the required buffer size.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error value. If pKeyName does not exist, the return value is ERROR_FILE_NOT_FOUND.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DeletePrinterDataEx, GetPrinterDataEx, OpenPrinter, SetPrinterDataEx


EnumPrinters

The EnumPrinters function enumerates available printers, print servers, domains, or print providers.

BOOL EnumPrinters(
  DWORD Flags,         // printer object types
  LPTSTR Name,         // name of printer object
  DWORD Level,         // information level
  LPBYTE pPrinterEnum, // printer information buffer
  DWORD cbBuf,         // size of printer information buffer
  LPDWORD pcbNeeded,   // bytes received or required
  LPDWORD pcReturned   // number of printers enumerated
);

Parameters

Flags
[in] Specifies the types of print objects that the function should enumerate. This value can be one or more of the following values.
Value | Meaning
PRINTER_ENUM_LOCAL The function ignores the Name parameter, and enumerates the locally installed printers.

Windows 95: The function will also enumerate network printers because they are handled by the local print provider.
PRINTER_ENUM_NAME | The function enumerates the printer identified by Name. This can be a server, a domain, or a print provider. If Name is NULL, the function enumerates available print providers.
PRINTER_ENUM_SHARED | The function enumerates printers that have the shared attribute. Cannot be used in isolation; use an OR operation to combine with another PRINTER_ENUM type.
PRINTER_ENUM_DEFAULT | Windows 95: The function returns information about the default printer.
PRINTER_ENUM_CONNECTIONS | Windows NT/2000 or later: The function enumerates the list of printers to which the user has made previous connections.
PRINTER_ENUM_NETWORK | Windows NT/2000 or later: The function enumerates network printers in the computer's domain. This value is valid only if Level is 1.
PRINTER_ENUM_REMOTE | Windows NT/2000 or later: The function enumerates network printers and print servers in the computer's domain. This value is valid only if Level is 1.

If Level is 4, you can only use the PRINTER_ENUM_CONNECTIONS and PRINTER_ENUM_LOCAL constants.

Name
[in] If Level is 1, Flags contains PRINTER_ENUM_NAME, and Name is non-NULL, then Name is a pointer to a null-terminated string that specifies the name of the object to enumerate. This string can be the name of a server, a domain, or a print provider.

If Level is 1, Flags contains PRINTER_ENUM_NAME, and Name is NULL, then the function enumerates the available print providers.

If Level is 1, Flags contains PRINTER_ENUM_REMOTE, and Name is NULL, then the function enumerates the printers in the user's domain.

If Level is 2 or 5, Name is a pointer to a null-terminated string that specifies the name of a server whose printers are to be enumerated. If this string is NULL, then the function enumerates the printers installed on the local machine.

If Level is 4, Name should be NULL. The function always queries on the local machine.

When Name is NULL, it enumerates printers that are installed on the local machine. These printers include those that are physically attached to the local machine as well as remote printers to which it has a network connection.

Level
[in] Specifies the type of data structures pointed to by pPrinterEnum. Valid values are 1, 2, 4, and 5, which correspond to the PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, and PRINTER_INFO_5 data structures.

Windows 95: The value can be 1, 2, or 5.

Windows NT/Windows 2000 or later: This value can be 1, 2, 4, or 5.

pPrinterEnum
[out] Pointer to a buffer that receives an array of PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, or PRINTER_INFO_5 structures. Each structure contains data that describes an available print object.

If Level is 1, the array contains PRINTER_INFO_1 structures. If Level is 2, the array contains PRINTER_INFO_2 structures. If Level is 4, the array contains PRINTER_INFO_4 structures. If Level is 5, the array contains PRINTER_INFO_5 structures.

The buffer must be large enough to receive the array of data structures and any strings or other data to which the structure members point. If the buffer is too small, the pcbNeeded parameter returns the required buffer size.

Windows 95: The buffer cannot receive PRINTER_INFO_4 structures. It can receive any of the other types.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pPrinterEnum.
pcbNeeded
[out] Pointer to a value that receives the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.
pcReturned
[out] Pointer to a value that receives the number of PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, or PRINTER_INFO_5 structures that the function returns in the array to which pPrinterEnum points.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If EnumPrinters returns a PRINTER_INFO_1 structure in which PRINTER_ENUM_CONTAINER is specified, this indicates that there is a hierarchy of printer objects. An application can enumerate the hierarchy by calling EnumPrinters again, setting Name to the value of the PRINTER_INFO_1 structure's pName member.

The EnumPrinters function does not retrieve security information. If PRINTER_INFO_2 structures are returned in the array pointed to by pPrinterEnum, their pSecurityDescriptor members will be set to NULL.

To get information about the default printer, call the GetProfileString function with the section name string set to "windows" and the key name string set to "device". The returned string contains the name of the default printer, the name of the printer DRV file, and the port to which the printer is attached.

Windows 2000 and later: To get information about the default printer, call GetDefaultPrinter

Windows NT/Windows 2000 or later: The PRINTER_INFO_4 structure provides an easy and extremely fast way to retrieve the names of the printers installed on a local machine, as well as the remote connections that a user has established. When EnumPrinters is called with a PRINTER_INFO_4 data structure, that function queries the registry for the specified information, then returns immediately. This differs from the behavior of EnumPrinters when called with other levels of PRINTER_INFO_* data structures. In particular, when EnumPrinters is called with a level 2 (PRINTER_INFO_2) data structure, it performs an OpenPrinter call on each remote connection. If a remote connection is down, or the remote server no longer exists, or the remote printer no longer exists, the function must wait for RPC to time out and consequently fail the OpenPrinter call. This can take a while. Passing a PRINTER_INFO_4 structure lets an application retrieve a bare minimium of required information; if more detailed information is desired, a subsequent EnumPrinter level 2 call can be made.

Windows 95: To quickly enumerate local and network printers, use the PRINTER_INFO_5 structure. This causes EnumPrinters to query the registry rather than make remote calls, and is similar to using the PRINTER_INFO_4 structure on Windows NT as described in the preceding paragraph.

Examples

The following table shows the EnumPrinters output for various Flags values when the Level parameter is set to 1.

In the Name parameter column of the table, you should substitute an appropriate name for Print Provider, Domain, and Machine. For example, for Print Provider, you could use the name of the Windows NT network print provider: "Windows NT Remote Printers", or the name of the Windows 95 local print provider: "Windows 95 Local Print Provider". To get print provider names, call EnumPrinters with Name set to NULL.

Flags parameter | Name parameter | Result
PRINTER_ENUM_LOCAL | The Name parameter is ignored. | All local printers. Windows 95: Also enumerates network printers because they are installed locally.
PRINTER_ENUM_NAME | "Print Provider" | All domain names
PRINTER_ENUM_NAME | Windows NT/2000 or later: "Print Provider!Domain" | All printers and print servers in the computer's domain
PRINTER_ENUM_NAME | Windows NT/2000 or later: "Print Provider!!\\Machine" | All printers shared at \\Machine
PRINTER_ENUM_NAME | Windows NT/2000 or later: An empty string, "" Windows 95: The name of the local machine or the local print provider. | All local printers. Windows 95: Also enumerates network printers because they are installed locally.
PRINTER_ENUM_NAME | NULL | All print providers in the computer's domain
Windows NT/2000 or later: PRINTER_ENUM_CONNECTIONS | The Name parameter is ignored. | All connected remote printers
Windows NT/2000 or later: PRINTER_ENUM_NETWORK | The Name parameter is ignored. | All printers in the computer's domain
Windows NT/2000 or later: PRINTER_ENUM_REMOTE | An empty string, "" | All printers and print servers in the computer's domain
Windows NT/2000 or later: PRINTER_ENUM_REMOTE | "Print Provider" | Same as PRINTER_ENUM_NAME
Windows NT/2000 or later: PRINTER_ENUM_REMOTE | "Print Provider!Domain" | All printers and print servers in computer's domain, regardless of Domain specified.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, DeletePrinter, GetPrinter, GetProfileString, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, PRINTER_INFO_5, SetPrinter


EnumPrintProcessorDatatypes

The EnumPrintProcessorDatatypes function enumerates the data types that a specifed print processor supports.

BOOL EnumPrintProcessorDatatypes(
  LPTSTR pName,                // printer server name
  LPTSTR pPrintProcessorName,  // print processor name
  DWORD Level,                 // information level
  LPBYTE pDatatypes,           // processor data buffer
  DWORD cbBuf,                 // size of data buffer
  LPDWORD pcbNeeded,           // bytes received or required
  LPDWORD pcReturned           // number of processors
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the print processor resides. If this parameter is NULL, the data types for the local print processor are enumerated.
pPrintProcessorName
[in] Pointer to a null-terminated string that specifies the name of the print processor whose data types are enumerated.
Level
[in] Specifies the type of information returned in the pDatatypes buffer. This parameter must be 1.
pDatatypes
[out] Pointer to a buffer that receives an array of DATATYPES_INFO_1 structures. Each structure describes an available data type. The buffer must be large enough to receive the array of structures and any strings or other data to which the structure members point.

To determine the required buffer size, call EnumPrintProcessorDatatypes with cbBuf set to zero. EnumPrintProcessorDatatypes fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pDatatypes.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied to the pDatatypes buffer if the function succeeds. If the buffer is too small, the function fails and the variable receives the number of bytes required.
pcReturned
[out] Pointer to a variable that receives the number of structures returned in the pDatatypes buffer. This is the number of supported data types.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DATATYPES_INFO_1, EnumPrintProcessors


EnumPrintProcessors

The EnumPrintProcessors function enumerates the print processors installed on the specified server.

BOOL EnumPrintProcessors(
  LPTSTR pName,                // print server name
  LPTSTR pEnvironment,         // environment name
  DWORD Level,                 // information level
  LPBYTE pPrintProcessorInfo,  // processor data buffer
  DWORD cbBuf,                 // size of data buffer
  LPDWORD pcbNeeded,           // bytes received or required
  LPDWORD pcReturned           // number of processors
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the print processors reside. If this parameter is NULL, the local print processors are enumerated.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
Level
[in] Specifies the type of information returned in the pPrintProcessorInfo buffer. This parameter must be 1.
pPrintProcessorInfo
[out] Pointer to a buffer that receives an array of PRINTPROCESSOR_INFO_1 structures. Each structure describes an available print processor. The buffer must be large enough to receive the array of structures and any strings to which the structure members point.

To determine the required buffer size, call EnumPrintProcessors with cbBuf set to zero. EnumPrintProcessors fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pPrintProcessorInfo.
pcbNeeded
[out] Pointer to a variable that receives the number of bytes copied to the pPrintProcessorInfo buffer if the function succeeds. If the buffer is too small, the function fails and the variable receives the number of bytes required.
pcReturned
[out] Pointer to a variable that receives the number of structures returned in the pPrintProcessorInfo buffer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrintProcessor, EnumPrintProcessorDatatypes, PRINTPROCESSOR_INFO_1


Escape

The Escape function enables applications to access capabilities of a particular device not directly available through GDI. Escape calls made by an application are translated and sent to the driver.

int Escape(
  HDC hdc,           // handle to DC
  int nEscape,       // escape function
  int cbInput,       // size of input structure
  LPCSTR lpvInData,  // input structure
  LPVOID lpvOutData  // output structure
);

Parameters

hdc
[in] Handle to the device context.
nEscape
[in] Specifies the escape function to be performed. This parameter must be one of the predefined escape values listed in the Remarks section. Use the ExtEscape function if your application defines a private escape value.
cbInput
[in] Specifies the number of bytes of data pointed to by the lpvInData parameter.
lpvInData
[in] Pointer to the input structure required for the specified escape.
lpvOutData
[out] Pointer to the structure that receives output from this escape. This parameter should be NULL if no data is returned.

Return Values

If the function succeeds, the return value is greater than zero, except with the QUERYESCSUPPORT printer escape, which checks for implementation only. If the escape is not implemented, the return value is zero.

If the function fails, the return value is an error.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Errors

If the function fails, the return value is one of the following values.

Value | Meaning
SP_ERROR | General error. If SP_ERROR is returned, Escape may set the last error code to: ERROR_INVALID_PARAMETER ERROR_DISK_FULL ERROR_NOT_ENOUGH_MEMORY ERROR_PRINT_CANCELLED
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 | The user terminated the job through Print Manager.

Remarks

Of the original printer escapes, only the following can be used by Win32-based applications.

Escape | Description
QUERYESCSUPPORT | Determines whether a particular escape is implemented by the device driver.
PASSTHROUGH | Allows the application to send data directly to a printer.

The following printer escapes are obsolete. They are provided only for compatibility with 16-bit versions of Windows.

Escape | Description
ABORTDOC | Stops the current print job and erases everything the application has written to the device since the last ENDDOC escape. In the Win32 API, this is superseded by AbortDoc.
ENDDOC | Ends a print job started by the STARTDOC escape. In the Win32 API, this is superseded by EndDoc.
GETPHYSPAGESIZE | Retrieves the physical page size and copies it to the specified location. In the Win32 API, this is superseded by PHYSICALWIDTH and PHYSICALHEIGHT in GetDeviceCaps.
GETPRINTINGOFFSET | Retrieves the offset from the upper-left corner of the physical page where the actual printing or drawing begins. In the Win32 API, this is superseded by PHYSICALOFFSETX and PHYSICALOFFSETY in GetDeviceCaps.
GETSCALINGFACTOR | Retrieves the scaling factors for the x-axis and the y-axis of a printer. In the Win32 API, this is superseded by SCALINGFACTORX and SCALINGFACTORY in GetDeviceCaps.
NEWFRAME | Informs the printer that the application has finished writing to a page. In the Win32 API, this is superseded by EndPage which ends a page. Unlike NEWFRAME, EndPage is always called after printing a page.
NEXTBAND | Informs the printer that the application has finished writing to a band. Band information is not used in Win32 applications.
SETABORTPROC | Sets the Abort function for a print job. In the Win32 API, this is superseded by SetAbortProc.
SETCOPYCOUNT | Sets the number of copies. In the Win32 API, this is superseded by DocumentProperties or PrinterProperties.
STARTDOC | Informs a printer driver that a new print job is starting. In the Win32 API, this is superseded by StartDoc.

In addition, the Win32 API has StartPage which is used to prepare the printer driver to receive data.

For an example, see Creating a Printer Device Context.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AbortDoc,DocumentProperties, EndDoc, EndPage, ExtEscape, GetDeviceCaps, PrinterProperties SetAbortProc, StartDoc, StartPage, ResetDC


ExtEscape

The ExtEscape function enables applications to access capabilities of a particular device that are not available through GDI.

int ExtEscape(
  HDC hdc,            // handle to DC
  int nEscape,        // escape function
  int cbInput,        // size of input structure
  LPCSTR lpszInData,  // input structure
  int cbOutput,       // size of output structure
  LPSTR lpszOutData   // output structure
);

Parameters

hdc
[in] Handle to the device context.
nEscape
[in] Specifies the escape function to be performed. It can be one of the following or it can be an application-defined escape function.
Value | Meaning
CHECKJPEGFORMAT | Windows 2000 or later: Checks whether the printer supports a JPEG image.
CHECKPNGFORMAT | Windows 2000 or later: Checks whether the printer supports a PNG image.
DRAWPATTERNRECT | Draws a white, gray-scale, or black rectangle.
GET_PS_FEATURESETTING | Windows 2000 or later: Gets information on a specified feature setting for a PostScript driver.
PASSTHROUGH | Allows the application to send data directly to a printer. Supported in compatibility mode and GDI-centric mode.
POSTSCRIPT_DATA | Allows the application to send data directly to a printer. Supported only in compatibility mode.
POSTSCRIPT_IDENTIFY | Windows 2000 or later: Sets a PostScript driver to GDI-centric or PostScript-centric mode.
POSTSCRIPT_INJECTION | Windows 2000 or later: Inserts a block of raw data in a PostScript job stream.
POSTSCRIPT_PASSTHROUGH | Windows 2000 or later: Sends data directly to a PostScript printer driver. Supported in compatibility mode and PS-centric mode.
QUERYESCSUPPORT | Determines whether a particular escape is implemented by the device driver.
SPCLPASSTHROUGH2 | Windows 2000 or later: Allows applications to include private procedures and other resources at the document level-save context.

cbInput
[in] Specifies the number of bytes of data pointed to by the lpszInData parameter.
lpszInData
[in] Pointer to the input structure required for the specified escape.
cbOutput
[in] Specifies the number of bytes of data pointed to by the lpszOutData parameter.
lpszOutData
[out] Pointer to the structure that receives output from this escape. This parameter must not be NULL if ExtEscape is called as a query function. If no data is to be returned in this structure, set cbOutput to 0.

Return Values

The return value specifies the outcome of the function. It is greater than zero if the function is successful, except for the QUERYESCSUPPORT printer escape, which checks for implementation only. The return value is zero if the escape is not implemented. A return value less than zero indicates an error.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

Use this function to pass a driver-defined escape value to a device.

Use the Escape function to pass one of the system-defined escape values to a device, unless the escape is one of the defined escapes in nEscape. ExtEscape might not work properly with the system-defined escapes. In particular, escapes in which lpszInData is a pointer to a structure that contains a member that is a pointer will fail.

For an example, see Sizing a JPEG or PNG Image.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, Escape, GetDeviceCaps


FindClosePrinterChangeNotification

The FindClosePrinterChangeNotification function closes a change notification object created by calling the FindFirstPrinterChangeNotification function. The printer or print server associated with the change notification object will no longer be monitored by that object.

BOOL FindClosePrinterChangeNotification(
  HANDLE hChange  // handle to change notification object
);

Parameters

hChange
[in] Handle to the change notification object to be closed. This is a handle created by calling the FindFirstPrinterChangeNotification function.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

After calling the FindClosePrinterChangeNotification function, you cannot use the hChange handle in subsequent calls to either FindFirstPrinterChangeNotification or FindNextPrinterChangeNotification.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, FindFirstPrinterChangeNotification, FindNextPrinterChangeNotification


FindFirstPrinterChangeNotification

The FindFirstPrinterChangeNotification function creates a change notification object and returns a handle to the object. You can then use this handle in a call to one of the wait functions to monitor changes to the printer or print server.

The FindFirstPrinterChangeNotification call specifies the type of changes to be monitored. You can specify a set of conditions to monitor for changes, a set of printer information fields to monitor, or both.

A wait operation on the change notification handle succeeds when one of the specified changes occurs in the specified printer or print server. You then call the FindNextPrinterChangeNotification function to retrieve information about the change, and to reset the change notification object for use in the next wait operation.

HANDLE FindFirstPrinterChangeNotification(
  HANDLE hPrinter,              // handle to printer
  DWORD fdwFlags,               // conditions to monitor
  DWORD fdwOptions,             // reserved, must be zero
  LPVOID pPrinterNotifyOptions  // fields to monitor
);

Parameters

hPrinter
[in] Handle to the printer or print server that you want to monitor. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
fdwFlags
[in] Specify the conditions that will cause the change notification object to enter a signaled state. A change notification occurs when one or more of the specified conditions are met. The fdwFlags parameter can be zero if pPrinterNotifyOptions is non-NULL.

This parameter can be one or more of the following values.
Value | Meaning
PRINTER_CHANGE_FORM Notify of any changes to a form. You can set this general flag or one or more of the following specific flags:
PRINTER_CHANGE_ADD_FORM PRINTER_CHANGE_SET_FORM PRINTER_CHANGE_DELETE_FORM
PRINTER_CHANGE_JOB Notify of any changes to a job. You can set this general flag or one or more of the following specific flags:
PRINTER_CHANGE_ADD_JOB PRINTER_CHANGE_SET_JOB PRINTER_CHANGE_DELETE_JOB PRINTER_CHANGE_WRITE_JOB
PRINTER_CHANGE_PORT Notify of any changes to a port. You can set this general flag or one or more of the following specific flags:
PRINTER_CHANGE_ADD_PORT PRINTER_CHANGE_CONFIGURE_PORT PRINTER_CHANGE_DELETE_PORT
PRINTER_CHANGE_PRINT_PROCESSOR | Notify of any changes to a print processor. You can set this general flag or one or more of the following specific flags: PRINTER_CHANGE_ADD_PRINT_PROCESSOR PRINTER_CHANGE_DELETE_PRINT_PROCESSOR
PRINTER_CHANGE_PRINTER Notify of any changes to a printer. You can set this general flag or one or more of the following specific flags:
PRINTER_CHANGE_ADD_PRINTER PRINTER_CHANGE_SET_PRINTER PRINTER_CHANGE_DELETE_PRINTER PRINTER_CHANGE_FAILED_CONNECTION_PRINTER
PRINTER_CHANGE_PRINTER_DRIVER Notify of any changes to a printer driver. You can set this general flag or one or more of the following specific flags:
PRINTER_CHANGE_ADD_PRINTER_DRIVER PRINTER_CHANGE_SET_PRINTER_DRIVER PRINTER_CHANGE_DELETE_PRINTER_DRIVER
PRINTER_CHANGE_ALL | Notify if any of the preceding changes occur.

For descriptions of the more specific flags in the preceding table, see the FindNextPrinterChangeNotification function.

fdwOptions
Reserved; must be zero.
pPrinterNotifyOptions
[in] Pointer to a PRINTER_NOTIFY_OPTIONS structure. The pTypes member of this structure is an array of one or more PRINTER_NOTIFY_OPTIONS_TYPE structures, each of which specifies a printer information field to monitor. A change notification occurs when one or more of the specified fields changes. When a change occurs, the FindNextPrinterChangeNotification function can retrieve the new printer information. This parameter can be NULL if fdwFlags is nonzero.

For a list of fields that can be monitored, see PRINTER_NOTIFY_OPTIONS_TYPE.

Return Values

If the function succeeds, the return value is a handle to a change notification object associated with the specified printer or print server.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

Remarks

To monitor a printer or print server, call the FindFirstPrinterChangeNotification function, then use the returned change notification object handle in a call to one of the wait functions. A wait operation on a change notification object is satisfied when the change notification object enters the signaled state. The system signals the object when one or more of the changes specified by fdwFlags or pPrinterNotifyOptions occurs in the monitored printer or print server.

When you call FindFirstPrinterChangeNotification, either fdwFlags must be nonzero or pPrinterNotifyOptions must be non-NULL. If both are specified, notifications will occur for both.

When a wait operation on a printer change notification object is satisfied, call the FindNextPrinterChangeNotification function to determine the cause of the notification. For a condition specified by fdwFlags, FindNextPrinterChangeNotification reports the condition or conditions that changed. For a printer information field specified by pPrinterNotifyOptions , FindNextPrinterChangeNotification reports the field or fields that changed as well as the new information for these fields. FindNextPrinterChangeNotification also resets the change notification object to the nonsignaled state so you can use it in another wait operation to continue monitoring the printer or print server.

Do not call the FindNextPrinterChangeNotification function if the change notification object is not in the signaled state. If the wait function returns the value WAIT_TIMEOUT, the change object is not in the signaled state. Call the FindNextPrinterChangeNotification function only if the wait function succeeds without timing out.

When you no longer need the change notification object, close it by calling the FindClosePrinterChangeNotification function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, FindClosePrinterChangeNotification, FindNextPrinterChangeNotification, OpenPrinter, PRINTER_NOTIFY_OPTIONS, PRINTER_NOTIFY_OPTIONS_TYPE


FindNextPrinterChangeNotification

The FindNextPrinterChangeNotification function retrieves information about the most recent change notification for a change notification object associated with a printer or print server. Call this function when a wait operation on the change notification object is satisfied.

The function also resets the change notification object to the not-signaled state. You can then use the object in another wait operation to continue monitoring the printer or print server. The operating system will set the object to the signaled state the next time one of a specified set of changes occurs to the printer or print server. The FindFirstPrinterChangeNotification function creates the change notification object and specifies the set of changes to be monitored.

BOOL FindNextPrinterChangeNotification(
  HANDLE hChange,                // change notification
  PDWORD pdwChange,              // condition that changed
  LPVOID pPrinterNotifyOptions,  // refresh option
  LPVOID *ppPrinterNotifyInfo    // printer information
);

Parameters

hChange
[in] Handle to a change notification object associated with a printer or print server. You obtain such a handle by calling the FindFirstPrinterChangeNotification function. The operating system sets this change notification object to the signaled state when it detects one of the changes specified in the object's change notification filter.
pdwChange
[out] Pointer to a doubleword variable whose bits are set to indicate the changes that occurred to cause the most recent notification. The bit flags that might be set correspond to those specified in the fdwFlags parameter of the FindFirstPrinterChangeNotification call. The system sets one or more of the following bit flags.
Value | Meaning
PRINTER_CHANGE_ADD_FORM | A form was added to the server.
PRINTER_CHANGE_ADD_JOB | A print job was sent to the printer.
PRINTER_CHANGE_ADD_PORT | A port or monitor was added to the server.
PRINTER_CHANGE_ADD_PRINT_PROCESSOR | A print processor was added to the server.
PRINTER_CHANGE_ADD_PRINTER | A printer was added to the server.
PRINTER_CHANGE_ADD_PRINTER_DRIVER | A printer driver was added to the server.
PRINTER_CHANGE_CONFIGURE_PORT | A port was configured on the server.
PRINTER_CHANGE_DELETE_FORM | A form was deleted from the server.
PRINTER_CHANGE_DELETE_JOB | A job was deleted.
PRINTER_CHANGE_DELETE_PORT | A port or monitor was deleted from the server.
PRINTER_CHANGE_DELETE_PRINT_PROCESSOR | A print processor was deleted from the server.
PRINTER_CHANGE_DELETE_PRINTER | A printer was deleted.
PRINTER_CHANGE_DELETE_PRINTER_DRIVER | A printer driver was deleted from the server.
PRINTER_CHANGE_FAILED_CONNECTION_PRINTER | A printer connection has failed.
PRINTER_CHANGE_SET_FORM | A form was set on the server.
PRINTER_CHANGE_SET_JOB | A job was set.
PRINTER_CHANGE_SET_PRINTER | A printer was set.
PRINTER_CHANGE_SET_PRINTER_DRIVER | A printer driver was set.
PRINTER_CHANGE_WRITE_JOB | Job data was written.
PRINTER_CHANGE_TIMEOUT | The job timed out.

pPrinterNotifyOptions
[in] Pointer to a PRINTER_NOTIFY_OPTIONS structure. Set the Flags member of this structure to PRINTER_NOTIFY_OPTIONS_REFRESH, to cause the function to return the current data for all monitored printer information fields. The function ignores all other members of the structure. This parameter can be NULL.
ppPrinterNotifyInfo
[out] Pointer to a pointer variable that receives a pointer to a system-allocated, read-only buffer. Call the FreePrinterNotifyInfo function to free the buffer when you are finished with it. This parameter can be NULL if no information is required.

The buffer contains a PRINTER_NOTIFY_INFO structure, which contains an array of PRINTER_NOTIFY_INFO_DATA structures. Each element of the array contains information about one of the fields specified in the pPrinterNotifyOptions parameter of the FindFirstPrinterChangeNotification call. Typically, the function provides data only for the fields that changed to cause the most recent notification. However, if the structure pointed to by the pPrinterNotifyOptions parameter specifies PRINTER_NOTIFY_OPTIONS_REFRESH, the function provides data for all monitored fields.

If the PRINTER_NOTIFY_INFO_DISCARDED bit is set in the Flags member of the PRINTER_NOTIFY_INFO structure, an overflow or error occurred, and notifications may have been lost. In this case, no additional notifications will be sent until you make a second FindNextPrinterChangeNotification call that specifies PRINTER_NOTIFY_OPTIONS_REFRESH.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Call the FindNextPrinterChangeNotification function after a wait operation on a notification object created by FindFirstPrinterChangeNotification has been satisfied. Calling FindNextPrinterChangeNotification lets you obtain information about the change that satisfied the wait operation, and resets the notification object so it can be signaled when the next change occurs.

Do not call the FindNextPrinterChangeNotification function if the change notification object is not in the signaled state. If a wait function returns the value WAIT_TIMEOUT, the change object is not in the signaled state. Call the FindNextPrinterChangeNotification function only if the wait function succeeds without timing out.

To continue monitoring the printer or print server for changes, repeat the cycle of calling one of the wait functions, and then calling the FindNextPrinterChangeNotification function to examine the change and reset the notification object.

FindNextPrinterChangeNotification may combine multiple changes to the same printer information field into a single notification. When this occurs, the function typically collapses all changes for the field into a single entry in the array of PRINTER_NOTIFY_INFO_DATA structures in ppPrinterNotifyInfo; the single entry reports only the most current information. However, for some job and printer information fields, the function can return multiple array entries for the same field. In this case, the last array entry for the field reports the current data, and the earlier entries contain the data for the intermediate stages.

When you no longer need the change notification object, close it by calling the FindClosePrinterChangeNotification function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, FindClosePrinterChangeNotification, FindFirstPrinterChangeNotification, PRINTER_NOTIFY_INFO, PRINTER_NOTIFY_INFO_DATA, PRINTER_NOTIFY_OPTIONS


FlushPrinter

The FlushPrinter function sends a buffer to the printer in order to clear it from a transient state.

BOOL FlushPrinter(
  HANDLE hPrinter,    // handle to printer object
  LPVOID pBuf,        // printer data buffer
  DWORD cbBuf,        // size of data buffer
  LPDWORD pcWritten,  // bytes received
  DWORD cSleep        // idle period
);

Parameters

hPrinter
[in] Handle to the printer object. This should be the same handle that was used, in a prior WritePrinter call, by the printer driver.
pBuf
[in] Pointer to an array of bytes that contains the data to be written to the printer.
cbBuf
[in] Specifies the size, in bytes, of the array pointed to by pBuf.
pcWritten
[out] Pointer to a value that receives the number of bytes of data that were written to the printer.
cSleep
[in] Specifies the time, in milliseconds, for which the I/O line to the printer port should be kept idle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

FlushPrinter should be called only if WritePrinter failed, leaving the printer in a transient state. For example, the printer could get into a transient state when the job gets aborted and the printer driver has partially sent some raw data to the printer.

FlushPrinter also can specify a idle period during which the print spooler does not schedule any jobs to the corresponding printer port.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, WritePrinter


FreePrinterNotifyInfo

The FreePrinterNotifyInfo function frees a system-allocated buffer created by the FindNextPrinterChangeNotification function.

BOOL FreePrinterNotifyInfo(
  PPRINTER_NOTIFY_INFO pPrinterNotifyInfo  // buffer
);

Parameters

pPrinterNotifyInfo
[in] Pointer to a PRINTER_NOTIFY_INFO buffer returned from a call to the FindNextPrinterChangeNotification function. FreePrinterNotifyInfo deallocates this buffer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, FindNextPrinterChangeNotification, PRINTER_NOTIFY_INFO


GetDefaultPrinter

The GetDefaultPrinter function retrieves the printer name of the default printer for the current user on the local computer.

BOOL GetDefaultPrinter(
  LPTSTR pszBuffer,   // printer name buffer
  LPDWORD pcchBuffer  // size of name buffer
);

Parameters

pszBuffer
[in] Pointer to a buffer that receives a null-terminated character string containing the default printer name. If this parameter is NULL, the function fails and the variable pointed to by pcchBuffer returns the required buffer size, in characters.
pcchBuffer
[in/out] On input, specifies the size, in characters, of the pszBuffer buffer. On output, receives the size, in characters, of the printer name string, including the terminating null character.

Return Values

If the function succeeds, the return value is a nonzero value and the variable pointed to by pcchBuffer contains the number of characters copied to the pszBuffer buffer, including the terminating null character.

If the function fails, the return value is zero. To get extended error information, call GetLastError, which can return one of the following error codes.

Value | Meaning
ERROR_INSUFFICIENT_BUFFER | The pszBuffer buffer is too small. The variable pointed to by pcchBuffer contains the required buffer size, in characters.
ERROR_FILE_NOT_FOUND | There is no default printer.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, SetDefaultPrinter


GetForm

The GetForm function retrieves information about a specified form.

BOOL GetForm(
  HANDLE hPrinter,   // handle to printer
  LPTSTR pFormName,  // form name
  DWORD Level,       // information level
  LPBYTE pForm,      // array of forms
  DWORD cbBuf,       // bytes in array
  LPDWORD pcbNeeded  // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pFormName
[in] Pointer to a null-terminated string that specifies the name of the form. To get the names of the forms supported by the printer, call the EnumForms function.
Level
[in] Specifies the version of the structure to which pForm points. This value must be 1.
pForm
[out] Pointer to an array of bytes that receives the initialized FORM_INFO_1 structure.
cbBuf
[in] Specifies the size, in bytes, of the pForm array.
pcbNeeded
[out] Pointer to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddForm, DeleteForm, OpenPrinter, SetForm


GetJob

The GetJob function retrieves information about a specified print job.

BOOL GetJob(
  HANDLE hPrinter,    // handle to printer
  DWORD JobId,        // job identifier
  DWORD Level,        // information level
  LPBYTE pJob,        // array of jobs
  DWORD cbBuf,        // bytes in array
  LPDWORD pcbNeeded   // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer for which the print-job data is retrieved. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
JobId
[in] Identifies the print job for which to retrieve data. Use the AddJob function or StartDoc function to get a print job identifier.
Level
[in] Specifies the type of information returned in the pJob buffer. If Level is 1, pJob receives a JOB_INFO_1 structure. If Level is 2, pJob receives a JOB_INFO_2 structure.
pJob
[out] Pointer to a buffer that receives a JOB_INFO_1 or a JOB_INFO_2 structure containing information about the job. The buffer must be large enough to store the strings pointed to by the structure members.

To determine the required buffer size, call GetJob with cbBuf set to zero. GetJob fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the array.
pcbNeeded
[out] Pointer to a value that specifies the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddJob, JOB_INFO_1, JOB_INFO_2, ScheduleJob, SetJob


GetPrinter

The GetPrinter function retrieves information about a specified printer.

BOOL GetPrinter(
  HANDLE hPrinter,    // handle to printer
  DWORD Level,        // information level
  LPBYTE pPrinter,    // printer information buffer
  DWORD cbBuf,        // size of buffer
  LPDWORD pcbNeeded   // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer for which the function retrieves information. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the level or type of structure that the function stores into the buffer pointed to by pPrinter.

Windows 95: This value can be 1, 2, or 5.

Windows NT/Windows 2000 or later: This value can be 1, 2, 3, 4, 5, 7, 8 or 9.

pPrinter
[out] Pointer to a buffer that receives a structure containing information about the specified printer. The buffer must be large enough to receive the structure and any strings or other data to which the structure members point. If the buffer is too small, the pcbNeeded parameter returns the required buffer size.

The type of structure is determined by the value of Level.
Level | Structure
1 | A PRINTER_INFO_1 structure containing general printer information.
2 | A PRINTER_INFO_2 structure containing detailed information about the printer.
3 | Windows NT/2000 or later: A PRINTER_INFO_3 structure containing the printer's security information.
4 | Windows NT/2000 or later: A PRINTER_INFO_4 structure containing minimal printer information, including the name of the printer, the name of the server, and whether the printer is remote or local.
5 | A PRINTER_INFO_5 structure containing printer information such as printer attributes and time-out settings.
7 | Windows 2000 or later: A PRINTER_INFO_7 structure that indicates whether the printer is published in the directory service.
8 | Windows 2000 or later: A PRINTER_INFO_8 structure specifying the global default printer settings.
9 | Windows 2000 or later: A PRINTER_INFO_9 structure specifying the per-user default printer settings.

cbBuf
[in] Specifies the size, in bytes, of the buffer pointed to by pPrinter.
pcbNeeded
[out] Pointer to a variable that the function sets to the size, in bytes, of the printer information. If cbBuf is smaller than this value, GetPrinter fails, and the value represents the required buffer size. If cbBuf is equal to or greater than this value, GetPrinter succeeds, and the value represents the number of bytes stored in the buffer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Note, the pDevMode member in the PRINTER_INFO_2, PRINTER_INFO_8, and PRINTER_INFO_9 structures can be NULL. When this happens, the printer is unusable until the driver is reinstalled successfully.

Windows NT/Windows 2000 or later: For the PRINTER_INFO_2 and PRINTER_INFO_3 structures that contain a pointer to a security descriptor, the function retrieves only those components of the security descriptor that the caller has permission to read. To retrieve particular security descriptor components, you must specify the necessary access rights when you call the OpenPrinter function to retrieve a handle to the printer. The following table shows the access rights required to read the various security descriptor components.

Access Right | Security Descriptor Component
READ_CONTROL | Owner Primary group Discretionary access-control list (DACL)
ACCESS_SYSTEM_SECURITY | System access-control list (SACL)

Windows 2000 or later: If you specify level 7, the dwAction member of PRINTER_INFO_7 returns one of the following values to indicate whether the printer is published in the directory service.

dwAction value | Meaning
DSPRINT_PUBLISH | The printer is published. The pszObjectGUID member contains the GUID of the directory services print queue object associated with the printer.
DSPRINT_UNPUBLISH | The printer is not published.
DSPRINT_PENDING | Indicates that the system is attempting to complete a publish or unpublish operation. If a SetPrinter call fails to publish or unpublish a printer, the system makes further attempts to complete the operation in the background.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AbortPrinter, AddPrinter, ClosePrinter, DeletePrinter, EnumPrinters, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4, PRINTER_INFO_5, PRINTER_INFO_7, PRINTER_INFO_8, PRINTER_INFO_9, OpenPrinter, SetPrinter


GetPrinterData

The GetPrinterData function retrieves configuration data for the specified printer or print server.

Windows 2000 or later: Calling GetPrinterData is equivalent to calling the GetPrinterDataEx function with the pKeyName parameter set to "PrinterDriverData".

DWORD GetPrinterData(
  HANDLE hPrinter,    // handle to printer or print server
  LPTSTR pValueName,  // value name
  LPDWORD pType,      // data type
  LPBYTE pData,       // configuration data buffer
  DWORD nSize,        // size of configuration data buffer
  LPDWORD pcbNeeded   // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer or print server for which the function retrieves configuration data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pValueName
[in] Pointer to a null-terminated string that identifies the data to retrieve.

For printers, this string is the name of a registry value under the printer's "PrinterDriverData" key in the registry.

For print servers, this string is one of the predefined strings listed in the following Remarks section.

pType
[out] Pointer to a variable that receives the type of data retrieved. The function returns the type specified in the SetPrinterData or SetPrinterDataEx call when the data was stored. This parameter can be NULL if you don't need the information.
pData
[out] Pointer to a buffer that receives the configuration data.
nSize
[in] Specifies the size, in bytes, of the buffer pointed to by pData.
pcbNeeded
[out] Pointer to a variable that receives the size, in bytes, of the configuration data. If the buffer size specified by nSize is too small, the function returns ERROR_MORE_DATA, and pcbNeeded indicates the required buffer size.

Windows 95/98/Me: If nSize is greater than zero, the behavior is as documented above. If nSize is zero, the return value is ERROR_SUCCESS and pcbNeeded returns the required buffer size.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS. If the function fails, the return value is an error value.

Remarks

GetPrinterData retrieves printer-configuration data set by the SetPrinterDataEx or SetPrinterData function.

If hPrinter is a handle to a print server, pValueName can specify one of the following predefined values.

SPLREG_DEFAULT_SPOOL_DIRECTORY
SPLREG_PORT_THREAD_PRIORITY_DEFAULT
SPLREG_PORT_THREAD_PRIORITY
SPLREG_SCHEDULER_THREAD_PRIORITY_DEFAULT
SPLREG_SCHEDULER_THREAD_PRIORITY
SPLREG_BEEP_ENABLED
SPLREG_NET_POPUP
SPLREG_EVENT_LOG
SPLREG_MAJOR_VERSION
SPLREG_MINOR_VERSION
SPLREG_ARCHITECTURE
SPLREG_OS_VERSION
Windows 2000 and later: SPLREG_OS_VERSIONEX
SPLREG_DS_PRESENT (On successful return, pData contains 0x0001 if the machine is on a DS domain, 0 otherwise.)
SPLREG_DS_PRESENT_FOR_USER (On successful return, pData contains 0x0001 if the user is logged onto a DS domain, 0 otherwise.)
SPLREG_REMOTE_FAX (On successful return, pData contains 0x0001 if the FAX service supports remote clients, 0 otherwise.)
SPLREG_NET_POPUP_TO_COMPUTER (On successful return, pData contains 1 if job notifications should be sent to the client computer, or 0 if job notifications are to be sent to the user.)
SPLREG_RETRY_POPUP (On successful return, pData contains 1 if server is set to retry PopUps for all jobs, or 0 if server does not retry PopUps for all jobs.)

In addition, the following values indicate pool printing behavior when an error occurs.

SPLREG_RESTART_JOB_ON_POOL_ERROR (Indicates the time, in seconds, when a job is restarted on another port after an error occurs. This is used with SPLREG_RESTART_JOB_ON_POOL_ENABLED.)
SPLREG_RESTART_JOB_ON_POOL_ENABLED (A nonzero value indicates that SPLREG_RESTART_JOB_ON_POOL_ERROR is enabled.)

The time specified in SPLREG_RESTART_JOB_ON_POOL_ERROR is a minimum time. The actual time can be longer, depending on the following port monitor settings, which are found under HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MonitorName\Ports.

Port monitor setting | Meaning
StatusUpdateEnabled | If a nonzero value, enables the port monitor to update the spooler with the port status.
StatusUpdateInterval | Specifies the interval, in seconds, when the port monitor updates the spooler with the port status.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetPrinterDataEx, OpenPrinter, SetPrinter, SetPrinterData, SetPrinterDataEx, PRINTPROCESSOR_CAPS_1


GetPrinterDataEx

The GetPrinterDataEx function retrieves configuration data for the specified printer or print server. GetPrinterDataEx can retrieve values stored by the SetPrinterData function. In addition, GetPrinterDataEx can retrieve values stored under a specified key by the SetPrinterDataEx function.

DWORD GetPrinterDataEx(
  HANDLE hPrinter,     // handle to printer or print server
  LPCTSTR pKeyName,    // registry key name
  LPCTSTR pValueName,  // registry value name
  LPDWORD pType,       // data type
  LPBYTE pData,        // configuration data buffer
  DWORD nSize,         // size of data buffer
  LPDWORD pcbNeeded    // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer or print server for which the function retrieves configuration data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key containing the value to be retrieved. Use the backslash ( \ ) character as a delimiter to specify a path that has one or more subkeys.

If hPrinter is a handle to a printer and pKeyName is NULL or an empty string, GetPrinterDataEx returns ERROR_INVALID_PARAMETER.

If hPrinter is a handle to a print server, pKeyName is ignored.

pValueName
[in] Pointer to a null-terminated string that identifies the data to retrieve.

For printers, this string specifies the name of a value under the pKeyName key.

For print servers, this string is one of the predefined strings listed in the following Remarks section.

pType
[out] Pointer to a variable that receives the type of data stored in the value. The function returns the type specified in the SetPrinterDataEx call when the data was stored. This parameter can be NULL if you don't need the information. GetPrinterDataEx passes pType on as the lpdwType parameter of a RegQueryValueEx function call.
pData
[out] Pointer to a buffer that receives the configuration data.
nSize
[in] Specifies the size, in bytes, of the buffer pointed to by pData.
pcbNeeded
[out] Pointer to a variable that receives the size, in bytes, of the configuration data. If the buffer size specified by nSize is too small, the function returns ERROR_MORE_DATA, and pcbNeeded indicates the required buffer size.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

GetPrinterDataEx retrieves printer-configuration data set by the SetPrinterDataEx and SetPrinterData functions.

If hPrinter is a handle to a print server, pValueName can specify one of the following predefined values.

SPLREG_ARCHITECTURE
SPLREG_BEEP_ENABLED
SPLREG_DEFAULT_SPOOL_DIRECTORY
SPLREG_DS_PRESENT (On successful return, pData contains 0x0001 if the machine is on a DS domain, 0 otherwise.)
SPLREG_DS_PRESENT_FOR_USER (On successful return, pData contains 0x0001 if the user is logged onto a DS domain, 0 otherwise.)
SPLREG_EVENT_LOG
SPLREG_MAJOR_VERSION
SPLREG_MINOR_VERSION
SPLREG_NET_POPUP
SPLREG_NET_POPUP_TO_COMPUTER (On successful return, pData contains 1 if job notifications should be sent to the client computer, or 0 if job notifications are to be sent to the user.)
SPLREG_OS_VERSION
Windows 2000 and later: SPLREG_OS_VERSIONEX
SPLREG_PORT_THREAD_PRIORITY_DEFAULT
SPLREG_PORT_THREAD_PRIORITY
SPLREG_REMOTE_FAX (On successful return, pData contains 0x0001 if the FAX service supports remote clients, 0 otherwise.)
SPLREG_RETRY_POPUP (On successful return, pData contains 1 if server is set to retry PopUps for all jobs, or 0 if server does not retry PopUps for all jobs.)
SPLREG_SCHEDULER_THREAD_PRIORITY_DEFAULT
SPLREG_SCHEDULER_THREAD_PRIORITY
SPLREG_W3SVCINSTALLED

In addition, the following values indicate pool printing behavior when an error occurs.

SPLREG_RESTART_JOB_ON_POOL_ERROR (Indicates the time, in seconds, when a job is restarted on another port after an error occurs. This is used with SPLREG_RESTART_JOB_ON_POOL_ENABLED.)
SPLREG_RESTART_JOB_ON_POOL_ENABLED (A nonzero value indicates that SPLREG_RESTART_JOB_ON_POOL_ERROR is enabled.)

The time specified in SPLREG_RESTART_JOB_ON_POOL_ERROR is a minimum time. The actual time can be longer, depending on the following port monitor settings, which are found under HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MonitorName\Ports.

Port monitor setting | Meaning
StatusUpdateEnabled | If a nonzero value, enables the port monitor to update the spooler with the port status.
StatusUpdateInterval | Specifies the interval, in seconds, when the port monitor updates the spooler with the port status.

Calling GetPrinterDataEx with the pKeyName parameter set to "PrinterDriverData" is equivalent to calling the GetPrinterData function.

If pKeyName is one of the predefined Directory Service (DS) keys (see SetPrinter) and pValueName contains a comma (','), then the portion of pValueName before the comma is used as the value name and the portion of pValueName to the right of the comma is used as the DS Property OID. A subkey called OID is created and a new value consisting of the value name and OID is entered under the OID key. SetPrinterDataEx also adds the value name and data under the DS key.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter, SetPrinterDataEx


GetPrinterDriver

The GetPrinterDriver function retrieves driver data for the specified printer.

Windows NT: In addition, if the driver is not installed on the local computer, GetPrinterDriver installs it.

BOOL GetPrinterDriver(
  HANDLE hPrinter,     // printer object
  LPTSTR pEnvironment, // environment name
  DWORD Level,         // information level
  LPBYTE pDriverInfo,  // driver data buffer
  DWORD cbBuf,         // size of buffer
  LPDWORD pcbNeeded    // bytes received or required
);

Parameters

hPrinter
[in] Handle to the printer for which the driver data should be retrieved. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
Level
[in] Specifies the printer driver structure returned in the pDriverInfo buffer. This parameter can be one of the following values.
Level | Structure
1 | DRIVER_INFO_1
2 | DRIVER_INFO_2
3 | Windows 95, Windows NT4.0 or later: DRIVER_INFO_3
4 | Windows 2000 or later: DRIVER_INFO_4
5 | Windows 2000 or later: DRIVER_INFO_5
6 | Windows Me, Windows 2000 or later: DRIVER_INFO_6

pDriverInfo
[out] Pointer to a buffer that receives a structure containing information about the driver, as specified by Level. The buffer must be large enough to store the strings pointed to by the structure members.

To determine the required buffer size, call GetPrinterDriver with cbBuf set to zero. GetPrinterDriver fails, GetLastError returns ERROR_INSUFFICIENT_BUFFER, and the pcbNeeded parameter returns the size, in bytes, of the buffer required to hold the array of structures and their data.

cbBuf
[in] Specifies the size, in bytes, of the array at which pDriverInfo points.
pcbNeeded
[out] Pointer to a value that receives the number of bytes copied if the function succeeds or the number of bytes required if cbBuf is too small.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Windows 95/98/Me: For a non-existent driver, the function returns ERROR_INVALID_NAMES.

Windows NT: For a non-existent driver, the function returns ERROR_UNKNOWN_PRINTER_DRIVER.

Remarks

The DRIVER_INFO_2, DRIVER_INFO_3, DRIVER_INFO_4, DRIVER_INFO_5, and DRIVER_INFO_6 structures contain a full path and file name specifying the location of the printer driver. An application can use the path and file name to load a printer driver by calling the LoadLibrary function and supplying the path and file name as the single argument.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriver, DRIVER_INFO_1, DRIVER_INFO_2, DRIVER_INFO_3, DRIVER_INFO_4, DRIVER_INFO_5, DRIVER_INFO_6, EnumPrinterDrivers, LoadLibrary, OpenPrinter


GetPrinterDriverDirectory

The GetPrinterDriverDirectory function retrieves the path of the printer-driver directory.

BOOL GetPrinterDriverDirectory(
  LPTSTR pName,             // server name
  LPTSTR pEnvironment,      // environment name
  DWORD Level,              // information level
  LPBYTE pDriverDirectory,  // path buffer
  DWORD cbBuf,              // size of path buffer
  LPDWORD pcbNeeded         // bytes received or required
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server on which the printer driver resides. If this parameter is NULL, the local driver-directory path is retrieved.

Windows 95/98/Me: This parameter must be NULL. The GetPrinterDriverDirectory function can only return the directory path of the local driver.

pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
Level
[in] Specifies the structure level. This value must be 1.
pDriverDirectory
[out] Pointer to a buffer that receives the path.
cbBuf
[in] Specifies the size of the buffer to which pDriverDirectory points.
pcbNeeded
[out] Pointer to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinterDriver


GetPrintProcessorDirectory

The GetPrintProcessorDirectory function retrieves the path for the print processor on the specified server.

BOOL GetPrintProcessorDirectory(
  LPTSTR pName,                // server name
  LPTSTR pEnvironment,         // environment name
  DWORD Level,                 // information level
  LPBYTE pPrintProcessorInfo,  // path buffer
  DWORD cbBuf,                 // size of path buffer
  LPDWORD pcbNeeded            // bytes received or required
);

Parameters

pName
[in] Pointer to a null-terminated string that specifies the name of the server. If this parameter is NULL, a local path is returned.
pEnvironment
[in] Pointer to a null-terminated string that specifies the environment (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0"). If this parameter is NULL, the current environment of the calling application and client machine (not of the destination application and print server) is used.
Level
[in] Specifies the structure level. This value must be 1.
pPrintProcessorInfo
[out] Pointer to a buffer that receives the path.
cbBuf
[in] Specifies the size of the buffer pointed to by pPrintProcessorInfo.
pcbNeeded
[out] Pointer to a value that specifies the number of bytes copied if the function succeeds, or the number of bytes required if cbBuf is too small.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrintProcessor


OpenPrinter

The OpenPrinter function retrieves a handle to the specified printer or print server.

BOOL OpenPrinter(
  LPTSTR pPrinterName,         // printer or server name
  LPHANDLE phPrinter,          // printer or server handle
  LPPRINTER_DEFAULTS pDefault  // printer defaults
);

Parameters

pPrinterName
[in] Pointer to a null-terminated string that specifies the name of the printer or print server.

Windows NT/2000 or later: If NULL, it indicates the local printer server.

phPrinter
[out] Pointer to a variable that receives a handle to the open printer or print server object.

Windows 2000 or later: The phPrinter parameter can return an Xcv handle for use with the XcvData function. For more information about XcvData, see the Microsoft Windows 2000 Driver Development Kit.

pDefault
[in] Pointer to a PRINTER_DEFAULTS structure. This value can be NULL.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The pDefault parameter enables you to specify the data type and device mode values that are used for printing documents submitted by the StartDocPrinter function. However, you can override these values by using the SetJob function after a document has been started.

You can call the OpenPrinter function to open a handle to a print server or to determine the access rights that a client has to a print server. To do so, specify the name of the print server in the pPrinterName parameter, set the pDatatype and pDevMode members of the PRINTER_DEFAULTS structure to NULL, and set the DesiredAccess member to specify a server access mask value such as SERVER_ALL_ACCESS. When you are finished with the handle, pass it to the ClosePrinter function to close it.

Windows 95/98/Me: OpenPrinter ignores the DesiredAccess member of PRINTER_DEFAULTS.

Windows NT/Windows 2000 or later: Use the DesiredAccess member of the PRINTER_DEFAULTS structure to specify the access rights that you need to the printer. The access rights can be one of the following.

Desired Access value | Meaning
PRINTER_ACCESS_ADMINISTER | To perform administrative tasks, such as those provided by SetPrinter.
PRINTER_ACCESS_USE | To perform basic printing operations.
PRINTER_ALL_ACCESS | To perform all administrative tasks and basic printing operations except for SYNCHRONIZE (see Standard Access Rights.
generic security values, such as WRITE_DAC | To allow specific control access rights. See Standard Access Rights.

If a user does not have permission to open a specified printer or print server with the desired access, the OpenPrinter call will fail, and GetLastError will return the value ERROR_ACCESS_DENIED.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, ClosePrinter, PRINTER_DEFAULTS, SetJob, SetPrinter, StartDocPrinter


PrinterProperties

The PrinterProperties function displays a printer-properties property sheet for the specified printer.

Windows 95: The PrinterProperties and DocumentProperties functions both display the same property sheet, which includes pages for setting document properties and printer properties.

BOOL PrinterProperties(
  HWND hWnd,        // handle to parent window
  HANDLE hPrinter   // handle to printer object
);

Parameters

hWnd
[in] Handle to the parent window of the property sheet.
hPrinter
[in] Handle to a printer object. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DocumentProperties, OpenPrinter


PrintWindow

[This is preliminary documentation and subject to change.]

The PrintWindow function copies a visual window into the specified device context (DC), typically a printer DC.

BOOL PrintWindow(
  HWND hwnd,               // Window to copy
  HDC  hdcBlt,             // HDC to print into
  UINT nFlags              // Optional flags
);

Parameters

hwnd
Handle to the window that will be copied.
hdcBlt
Handle to the device context.
nFlags
Specifies the drawing options. It can be one of the following values.
Value | Meaning
PW_CLIENTONLY | Only the client area of the window is copied to hdcBlt. By default, the entire window is copied.

Return Values

If the function succeeds, it returns a nonzero value.

If the function fails, it returns zero.

Remarks

This function is similar to WM_PRINT. Before calling PrintWindow, first select a bitmap into hdcBlt.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Painting and Drawing Overview, Painting and Drawing Messages, WM_PRINT


ReadPrinter

The ReadPrinter function retrieves data from the specified printer.

BOOL ReadPrinter(
  HANDLE hPrinter,      // handle to printer object
  LPVOID pBuf,          // data buffer
  DWORD cbBuf,          // size of data buffer
  LPDWORD pNoBytesRead  // bytes received
);

Parameters

hPrinter
[in] Handle to the printer for which to retrieve data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pBuf
[out] Pointer to a buffer that receives the printer data.
cbBuf
[in] Specifies the size, in bytes, of the buffer to which pBuf points.
pNoBytesRead
[out] Pointer to a variable that receives the number of bytes of data copied into the array to which pBuf points.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

ReadPrinter returns an error if the device or the printer is not bidirectional.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter


ResetPrinter

The ResetPrinter function specifies the data type and device mode values to be used for printing documents submitted by the StartDocPrinter function. These values can be overridden by using the SetJob function after document printing has started.

BOOL ResetPrinter(
  HANDLE hPrinter,             // handle to printer
  LPPRINTER_DEFAULTS pDefault  // printer defaults
);

Parameters

hPrinter
[in] Handle to the printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pDefault
[in] Pointer to a PRINTER_DEFAULTS structure.

The ResetPrinter function ignores the DesiredAccess member of the PRINTER_DEFAULTS structure. Set that member to zero.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter, PRINTER_DEFAULTS, StartDocPrinter, SetJob


ScheduleJob

The ScheduleJob function requests that the print spooler schedule a specified print job for printing.

BOOL ScheduleJob(
  HANDLE hPrinter,  // handle to printer
  DWORD dwJobID     // print job identifier
);

Parameters

hPrinter
[in] Handle to the printer for the print job. This must be a local printer that is configured as a spooled printer. If hPrinter is a handle to a remote printer connection, or if the printer is configured for direct printing, the ScheduleJob function fails. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

hPrinter must be the same printer handle specifed in the call to AddJob that obtained the dwJobID print job identifer.

dwJobID
[in] Specifies the print job to be scheduled. You obtain this print job identifer by calling the AddJob function.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

You must successfully call the AddJob function before calling the ScheduleJob function. AddJob obtains the print job identifer that you pass to ScheduleJob as dwJobID. Both calls must use the same value for hPrinter.

The ScheduleJob function checks for a valid spool file. If there is an invalid spool file, or if it is empty, ScheduleJob deletes both the spool file and the corresponding print job entry in the print spooler.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddJob, OpenPrinter


SetAbortProc

The SetAbortProc function sets the application-defined abort function that allows a print job to be canceled during spooling.

int SetAbortProc(
  HDC hdc,                // handle to DC
  ABORTPROC lpAbortProc   // abort function
);

Parameters

hdc
[in] Handle to the device context for the print job.
lpAbortProc
[in] Pointer to the application-defined abort function. For more information about the callback function, see the AbortProc callback function.

Return Values

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is SP_ERROR.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

For an example, see Preparing to Print.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AbortDoc, AbortProc


SetDefaultPrinter

The SetDefaultPrinter function sets the printer name of the default printer for the current user on the local computer.

BOOL SetDefaultPrinter(
  LPCTSTR pszPrinter  // default printer name
);

Parameters

pszPrinter
[in] Pointer to a null-terminated string containing the default printer name. For a remote printer, the name format is \\server\printername. For a local printer, the name format is printername.

If this parameter is NULL or an empty string, that is, "", SetDefaultPrinter does nothing if there is already a default printer. However, if there is no default printer, SetDefaultPrinter sets the default printer to the first printer, if any, in an enumeration of printers installed on the local computer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

To set the default printer on Windows 2000, call SetDefaultPrinter. To set the default printer to earlier operating systems, call GetProfileString, WriteProfileString, and SendNotifyMessage, as shown in the following code:

        // read PrinterPorts section from win.ini
        // returned string should be of the form "driver,port,timeout,timeout", i.e. "winspool,LPT1:,15,45".
GetProfileString(TEXT("Windows"),TEXT("Device"),_T(",,,"),m_szName, COUNTOF(m_szName));
WriteProfileString(TEXT("Windows"),TEXT("Device"),pszPrinterName ));
        // Notify all open applications of the change. Note, only applications that handle the message will recognize the change.
#if WM_WININICHANGE != WM_SETTINGCHANGE
        // Old message type; for windows95
SendNotifyMessage(HWND_BROADCAST,WM_WININICHANGE,0,(LPARAM)szWindows);
#endif
        // New message type
SendNotifyMessage(HWND_BROADCAST,WM_SETTINGCHANGE,0,(LPARAM)szWindows);

When using this method, you must specify a valid printer, driver, and port. If they are invalid, the APIs do not fail but the result is not defined. This could cause other programs to set the printer back to the previous valid printer. You can use EnumPrinters to retrieve the printer name, driver name, and port name of all available printers.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EnumPrinters, GetDefaultPrinter, GetProfileString, WriteProfileString, SendNotifyMessage


SetForm

The SetForm function sets the form information for the specified printer.

BOOL SetForm(
  HANDLE hPrinter,  // handle to printer object
  LPTSTR pFormName, // form name
  DWORD Level,      // information level
  LPBYTE pForm      // form buffer
);

Parameters

hPrinter
[in] Handle to the printer for which the form information is set. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pFormName
[in] Pointer to a null-terminated string that specifies the form name for which the form information is set.
Level
[in] Specifies the version of the structure to which pForm points. This value must be 1.
pForm
[in] Pointer to a FORM_INFO_1 structure.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetForm, OpenPrinter, FORM_INFO_1


SetJob

The SetJob function pauses, resumes, cancels, or restarts a print job on a specified printer. You can also use the SetJob function to set print job parameters, such as the print job priority and the document name.

Windows 95: You can use the SetJob function to give a command to a print job, or to set print job parameters, but you can not do both in the same call. Thus, when the Command parameter is nonzero, the function ignores the Level and pJob parameters. To set print job parameters, you must set Command to 0.

Windows NT/Windows 2000 or later: You can use the SetJob function to give a command to a print job, or to set print job parameters, or you can do both in the same call. The value of the Command parameter does not affect how the function uses the Level and pJob parameters.

BOOL SetJob(
  HANDLE hPrinter,  // handle to printer object
  DWORD JobId,      // print job identifier
  DWORD Level,      // information level
  LPBYTE  pJob,     // job information buffer
  DWORD Command     // job command value
);

Parameters

hPrinter
[in] Handle to the printer object of interest. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
JobId
[in] Identifier that specifies the print job. You obtain a print job identifier by calling the AddJob function or the StartDoc function.

Windows NT/Windows 2000 or later: If the Level parameter is set to 3, the JobId parameter must match the JobId member of the JOB_INFO_3 structure pointed to by pJob.

Level
[in] Specifies the type of job information structure pointed to by the pJob parameter. You can set the Level parameter to 0, 1, or 2.

When you set Level to 0, pJob should be NULL. Use these values when you are not setting any print job parameters.

Windows NT/Windows 2000 or later: You can also set the Level parameter to 3.

Windows 95: The function pays attention to this parameter only if the Command parameter is 0. If Command is nonzero, the function ignores this parameter and the pJob parameter.

pJob
[in] Pointer to a JOB_INFO_1 or JOB_INFO_2 structure. The function uses this structure to set print job parameters.

Windows NT/Windows 2000 or later: pJob can also point to a JOB_INFO_3 structure.

If the Level parameter is 0, pJob should be NULL.

If the Level parameter is 1, pJob should point to a JOB_INFO_1 structure. If the Level parameter is 2, pJob should point to a JOB_INFO_2 structure.

Windows NT/Windows 2000 or later: If the Level parameter is 3, pJob should point to a JOB_INFO_3 structure. You must have JOB_ACCESS_ADMINISTER access permission for the jobs specified by the JobId and NextJobId members of the JOB_INFO_3 structure.

Windows 95: The function pays attention to this parameter only if the Command parameter is 0. If Command is nonzero, the function ignores this parameter and the Level parameter.

Command
[in] Specifies the print job operation to perform. This parameter can be one of the following values.
Value | Meaning
JOB_CONTROL_CANCEL Windows 95/98, Windows NT 3.51 and earlier: Delete the print job.

Windows NT 4.0 and later: Do not use. To delete a print job, use JOB_CONTROL_DELETE.
JOB_CONTROL_PAUSE | Pause the print job.
JOB_CONTROL_RESTART | Restart the print job. A job can only be restarted if it was printing.
JOB_CONTROL_RESUME | Resume a paused print job.
JOB_CONTROL_DELETE | Windows NT 4.0 and later: Delete the print job.
JOB_CONTROL_SENT_TO_PRINTER | Windows NT 4.0 and later: Used by langauge monitors to end the print job.
JOB_CONTROL_LAST_PAGE_EJECTED | Windows NT 4.0 and later: Used by port monitors to end the print job.

Windows 95: If you are using the SetJob function to set print job parameters, you must set the Command parameter to 0.

Windows NT/Windows 2000 or later: You can use the same call to the SetJob function to set print job parameters and to give a command to a print job. Thus, Command does not need to be 0 if you are setting print job parameters, although it can be.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

You can use the SetJob function to set various print job parameters by supplying a pointer to a JOB_INFO_1, JOB_INFO_2, or JOB_INFO_3 structure that contains the necessary data.

Windows 95: When you use the function to set print job parameters, you must set the Command parameter to 0.

To remove or delete all of the print jobs for a particular printer, call the SetPrinter function with its Command parameter set to PRINTER_CONTROL_PURGE.

The following members of a JOB_INFO_1 or JOB_INFO_2 structure are ignored on a call to SetJob:

JobId, pPrinterName, pMachineName, pDrivername, Size, Submitted, Time, and TotalPages.

You must have PRINTER_ACCESS_ADMINISTER access permission for a printer in order to change a print job's position in the print queue.

If you do not want to set a print job's position in the print queue, you should set the Position member of the JOB_INFO_1 or JOB_INFO_2 structure to JOB_POSITION_UNSPECIFIED.

Windows NT/Windows 2000 or later: Use the SetJob function with the JOB_INFO_3 structure to link together a set of print jobs. This can be useful in situations where a single document consists of several parts that you want to render separately.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddJob, GetJob, OpenPrinter, SetPrinter, JOB_INFO_1, JOB_INFO_2, JOB_INFO_3


SetPort

The SetPort function sets the status associated with a printer port.

BOOL SetPort(
  LPTSTR pName,      // printer server name
  LPTSTR pPortName,  // printer port name
  DWORD dwLevel,     // information level
  LPBYTE pPortInfo   // information buffer
);

Parameters

pName
[in] Pointer to a zero-terminated string that specifies the name of the printer server to which the port is connected. Set this parameter to NULL if the port is on the local machine.
pPortName
[in] Pointer to a zero-terminated string that specifies the name of the printer port.
dwLevel
[in] Specifies the type of structure pointed to by the pPortInfo parameter.

This value must be 3, which corresponds to a PORT_INFO_3 data structure.

pPortInfo
[in] Pointer to a PORT_INFO_3 structure that contains the port status information to set.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The caller of the SetPort function must have SERVER_ACCESS_ADMINISTER access to the server to which the port is connected.

When you set a printer port status value with the severity value PORT_STATUS_TYPE_ERROR, the print spooler stops sending jobs to the port. The print spooler resumes sending jobs to the port when the port status is cleared by another call to SetPort.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, PORT_INFO_3


SetPrinter

The SetPrinter function sets the data for a specified printer or sets the state of the specified printer by pausing printing, resuming printing, or clearing all print jobs.

BOOL SetPrinter(
  HANDLE hPrinter,  // handle to printer object
  DWORD Level,      // information level
  LPBYTE pPrinter,  // printer data buffer
  DWORD Command     // printer-state command
);

Parameters

hPrinter
[in] Handle to the printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the type of data that the function stores into the buffer pointed to by pPrinter. If the Command parameter is not equal to zero, the Level parameter must be zero.

Windows 95: This value can be 0, 2, or 5.

Windows NT/Windows 2000 or later: This value can be 0, 2, 3, 4, 5, 7, 8, or 9.

pPrinter
[in] Pointer to a buffer containing data to set for the printer, or containing information for the command specified by the Command parameter. The type of data in the buffer is determined by the value of Level.
Level | Structure
0 If the Command parameter is PRINTER_CONTROL_SET_STATUS, pPrinter must contain a DWORD value that specifies the new printer status to set. For a list of the possible status values, see the Status member of the PRINTER_INFO_2 structure. Note that PRINTER_STATUS_PAUSED and PRINTER_STATUS_PENDING_DELETION are not valid status values to set.

If Level is 0, but the Command parameter is not PRINTER_CONTROL_SET_STATUS, pPrinter must be NULL.

2 | A PRINTER_INFO_2 structure containing detailed information about the printer.
3 | Windows NT/2000 or later: A PRINTER_INFO_3 structure containing the printer's security information.
4 | Windows NT/2000 or later: A PRINTER_INFO_4 structure containing minimal printer information, including the name of the printer, the name of the server, and whether the printer is remote or local.
5 | A PRINTER_INFO_5 structure containing printer information such as printer attributes and time-out settings.
7 | Windows 2000 or later: A PRINTER_INFO_7 structure. The dwAction member of this structure indicates whether SetPrinter should publish, unpublish, re-publish, or update the printer's data in the directory service.
8 | Windows 2000 or later: A PRINTER_INFO_8 structure specifying the global default printer settings.
9 | Windows 2000 or later: A PRINTER_INFO_9 structure specifying the per-user default printer settings.

Command
[in] Specifies the action performed by the SetPrinter function.

If the Level parameter is nonzero, Command must be zero. In this case, the printer retains its current state and the function reconfigures the printer data as specified by the Level and pPrinter parameters.

If the Level parameter is zero, Command can be one of the following values to set the state of the printer.
Value | Meaning
PRINTER_CONTROL_PAUSE | Pauses the printer.
PRINTER_CONTROL_PURGE | Deletes all print jobs in the printer.
PRINTER_CONTROL_RESUME | Resumes a paused printer.
PRINTER_CONTROL_SET_STATUS | Sets the printer status. The pPrinter parameter is a pointer to a DWORD that specifies the new printer status.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Windows 2000 or later: If Level is 7 and the publish action failed, SetPrinter returns ERROR_IO_PENDING and attempts to complete the action in the background. If Level is 7 and the update action failed, SetPrinter returns ERROR_FILE_NOT_FOUND.

Remarks

Note that for Windows 95/98 and Windows NT 4.0 and earlier, you cannot use SetPrinter to change the default printer. For more information, see Printer Output.

To modify the current printer settings, call the GetPrinter function to retrieve the current settings into a PRINTER_INFO_2 structure, modify the members of that structure as necessary, and then call SetPrinter.

The SetPrinter function ignores the pServerName, AveragePPM, Status, and cJobs members of a PRINTER_INFO_2 structure.

Pausing a printer suspends scheduling of all print jobs for that printer, except for the one print job that may be currently printing. Print jobs can be submitted to a paused printer, but no jobs will be scheduled to print on that printer until printing is resumed. If a printer is cleared, all print jobs for that printer are deleted, except for the current print job.

If you use SetPrinter to modify the default DEVMODE structure for a printer (globally setting the printer defaults), you must first call the DocumentProperties function to validate the DEVMODE structure.

Windows NT/Windows 2000 or later: For the PRINTER_INFO_2 and PRINTER_INFO_3 structures that contain a pointer to a security descriptor, the function can set only those components of the security descriptor that the caller has permission to modify. To set particular security descriptor components, you must specify the necessary access rights when you call the OpenPrinter function to retrieve a handle to the printer. The following table shows the access rights required to modify the various security descriptor components.

Access permission | Security descriptor component
WRITE_OWNER | Owner Primary proup
WRITE_DAC | Discretionary access-control list (DACL)
ACCESS_SYSTEM_SECURITY | System access-control list (SACL)

If the security descriptor contains a component that the caller does not have the access right to modify, SetPrinter fails. Those components of a security descriptor that you don't want to modify should be NULL or not be present, as appropriate. If you do not want to modify the security descriptor, and are calling SetPrinter with a PRINTER_INFO_2 structure, set the pSecurityDescriptor member of that structure to NULL.

Windows 2000 or later: You can use level 7 with the PRINTER_INFO_7 structure to publish, unpublish, or update directory service data for the printer. The directory service data for a printer includes all the data stored under the SPLDS_* keys by calls to the SetPrinterDataEx function for the printer. Before calling SetPrinter, set the pszObjectGUID member of PRINTER_INFO_7 to NULL and set the dwAction member to one of the following values.

Value | Description
DSPRINT_PUBLISH | Publishes the directory service data.
DSPRINT_REPUBLISH | The directory service data for the printer is unpublished and then published again, refreshing all properties in the published printer. Re-publishing also changes the GUID of the published printer. Use this value if you suspect the printer's published data has been corrupted.
DSPRINT_UNPUBLISH | Unpublishes the directory service data.
DSPRINT_UPDATE | Updates the directory service data. This is the same as DSPRINT_PUBLISH, except that SetPrinter fails with ERROR_FILE_NOT_FOUND if the printer is not already published. Use DSPRINT_UPDATE to update published properties but not force publishing. Printer drivers should always use DSPRINT_UPDATE rather than DSPRINT_PUBLISH.

DSPRINT_PENDING is not a valid dwAction value for SetPrinter.

Windows 95: SetPrinter does not update the pShareName member in the PRINTER_INFO_2 structure.

You cannot call SetPrinter from a Windows 95 computer to set the data for a Windows NT printer using the printer's UNC name.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, AddPrinter, GetPrinter, OpenPrinter, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4, PRINTER_INFO_5, PRINTER_INFO_6, PRINTER_INFO_7, PRINTER_INFO_8, PRINTER_INFO_9, SetPrinterDataEx


SetPrinterData

The SetPrinterData function sets the configuration data for a printer or print server.

Windows 2000 or later: To specify the registry key under which to store the data, call the SetPrinterDataEx function. Calling SetPrinterData is equivalent to calling the SetPrinterDataEx function with the pKeyName parameter set to "PrinterDriverData".

DWORD SetPrinterData(
  HANDLE hPrinter,    // handle to printer or print server
  LPTSTR pValueName,  // data to set
  DWORD Type,         // data type
  LPBYTE pData,       // configuration data buffer
  DWORD cbData        // size of buffer
);

Parameters

hPrinter
[in] Handle to the printer or print server for which the function sets configuration data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pValueName
[in] Pointer to a null-terminated string that identifies the data to set.

For printers, this string is the name of a registry value under the printer's "PrinterDriverData" key in the registry.

For print servers, this string is one of the predefined strings listed in the following Remarks section.

Windows 95/98/Me: pValueName cannot be NULL.

Type
[in] Specifies a code indicating the type of data pointed to by the pData parameter. For a list of the possible type codes, see Registry Value Types.
pData
[in] Pointer to an array of bytes that contains the printer configuration data.
cbData
[in] Specifies the size, in bytes, of the array.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

To retrieve existing configuration data for a printer, call the GetPrinterDataEx or GetPrinterData function.

If hPrinter is a handle to a print server, pValueName can specify one of the following predefined values.

SPLREG_DEFAULT_SPOOL_DIRECTORY
SPLREG_PORT_THREAD_PRIORITY_DEFAULT
SPLREG_PORT_THREAD_PRIORITY
SPLREG_SCHEDULER_THREAD_PRIORITY_DEFAULT
SPLREG_SCHEDULER_THREAD_PRIORITY
SPLREG_BEEP_ENABLED
SPLREG_NET_POPUP
SPLREG_EVENT_LOG
SPLREG_MAJOR_VERSION
SPLREG_MINOR_VERSION
SPLREG_ARCHITECTURE
SPLREG_OS_VERSION
Windows 2000 and later: SPLREG_OS_VERSIONEX
SPLREG_NET_POPUP_TO_COMPUTER (pData contains 1 if job notifications should be sent to the client computer, or 0 if job notifications are to be sent to the user.)
SPLREG_RETRY_POPUP (pData contains 1 if server should be set to retry PopUps for all jobs, or 0 if server should be set to not retry PopUps for all jobs. The default is 1.)

In addition, the following values determine pool printing behavior when an error occurs.

SPLREG_RESTART_JOB_ON_POOL_ERROR (Indicates the time, in seconds, when a job is restarted on another port after an error occurs. This is used with SPLREG_RESTART_JOB_ON_POOL_ENABLED.)
SPLREG_RESTART_JOB_ON_POOL_ENABLED (A nonzero value indicates that SPLREG_RESTART_JOB_ON_POOL_ERROR is enabled.)

The time specified in SPLREG_RESTART_JOB_ON_POOL_ERROR is a minimum time. The actual time can be longer, depending on the following port monitor settings, which are found under HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MonitorName\Ports.

Port monitor setting | Meaning
StatusUpdateEnabled | If a nonzero value, enables the port monitor to update the spooler with the port status.
StatusUpdateInterval | Specifies the interval, in seconds, when the port monitor updates the spooler with the port status.

To ensure that the spooler redirects jobs to the next available printer in the pool (when the print job is not printed within the set time), the port monitor must support SNMP (see table, following), and the network ports in the pool must be configured as "SNMP status enabled."

OS version | Port monitor that supports SNMP
Windows NT 4.0 | HP Standard TCP/IP port monitor.
Windows 2000 | Standard TCP/IP port monitor

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetPrinter, GetPrinterData, GetPrinterDataEx, OpenPrinter, SetPrinterDataEx


SetPrinterDataEx

The SetPrinterDataEx function sets the configuration data for a printer or print server. The function stores the configuration data under the printer's registry key.

DWORD SetPrinterDataEx(
  HANDLE hPrinter,     // handle to printer or print server
  LPCTSTR pKeyName,    // registry key name
  LPCTSTR pValueName,  // registry value name
  DWORD Type,          // data type
  LPBYTE pData,        // configuration data buffer
  DWORD cbData         // size of configuration data buffer
);

Parameters

hPrinter
[in] Handle to the printer or print server for which the function sets configuration data. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pKeyName
[in] Pointer to a null-terminated string that specifies the key containing the value to set. If the specified key or subkeys do not exist, the function creates them.

To store configuration data that can be published in the directory service (DS), specify one of the following predefined registry keys.
Value | Meaning
SPLDS_DRIVER_KEY | Printer drivers use this key to store driver properties.
SPLDS_SPOOLER_KEY | Reserved. Used only by the print spooler to store internal spooler properties.
SPLDS_USER_KEY | Applications use this key to store printer properties such as printer asset numbers.

Values stored under the the SPLDS_USER_KEY key are published in the directory service only if there is a corresponding property in the schema. A domain administrator must create the property if it doesn't already exist. To publish a user-defined property after you use SetPrinterDataEx to add or change a value, call SetPrinter with Level = 7 and with PRINTER_INFO_7.dwAction set to DSPRINT_UPDATE.

You can specify other keys to store non-DS configuration data. Use the backslash ( \ ) character as a delimiter to specify a path that has one or more subkeys.

If hPrinter is a handle to a printer and pKeyName is NULL or an empty string, SetPrinterDataEx returns ERROR_INVALID_PARAMETER.

If hPrinter is a handle to a print server, pKeyName is ignored.

Note, do not use SPLDS_SPOOLER_KEY. In order to change the spooler printer properties, use SetPrinter with Level = 2.

pValueName
[in] Pointer to a null-terminated string that identifies the data to set.

For printers, this string specifies the name of a value under the pKeyName key.

For print servers, this string is one of the predefined strings listed in the following Remarks section.

Type
[in] Specifies a code indicating the type of data pointed to by the pData parameter. For a list of the possible type codes, see Registry Value Types.

If pKeyName specifies one of the predefined directory service keys, Type must be REG_SZ, REG_MULTI_SZ, REG_DWORD, or REG_BINARY. If REG_BINARY is used, cbData must be equal to 1, and the directory service treats the data as a Boolean value.

pData
[in] Pointer to a buffer that contains the printer configuration data.
cbData
[in] Specifies the size, in bytes, of the array.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is an error value.

Remarks

To retrieve existing configuration data for a printer, call the GetPrinterDataEx function.

If hPrinter is a handle to a print server, pValueName can specify one of the following predefined values.

SPLREG_DEFAULT_SPOOL_DIRECTORY
SPLREG_PORT_THREAD_PRIORITY_DEFAULT
SPLREG_PORT_THREAD_PRIORITY
SPLREG_SCHEDULER_THREAD_PRIORITY_DEFAULT
SPLREG_SCHEDULER_THREAD_PRIORITY
SPLREG_BEEP_ENABLED
SPLREG_NET_POPUP
SPLREG_EVENT_LOG
SPLREG_MAJOR_VERSION
SPLREG_MINOR_VERSION
SPLREG_ARCHITECTURE
SPLREG_OS_VERSION
Windows 2000 and later: SPLREG_OS_VERSIONEX
SPLREG_NET_POPUP_TO_COMPUTER (pData contains 1 if job notifications should be sent to the client computer, or 0 if job notifications are to be sent to the user.)
SPLREG_RETRY_POPUP (pData contains 1 if server should be set to retry PopUps for all jobs, or 0 if server should be set to not retry PopUps for all jobs. The default is 1.)

In addition, the following values determine pool printing behavior when an error occurs.

SPLREG_RESTART_JOB_ON_POOL_ERROR (Indicates the time, in seconds, when a job is restarted on another port after an error occurs. This is used with SPLREG_RESTART_JOB_ON_POOL_ENABLED.)
SPLREG_RESTART_JOB_ON_POOL_ENABLED (A nonzero value indicates that SPLREG_RESTART_JOB_ON_POOL_ERROR is enabled.)

The time specified in SPLREG_RESTART_JOB_ON_POOL_ERROR is a minimum time. The actual time can be longer, depending on the following port monitor settings, which are found under HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MonitorName\Ports.

Port monitor setting | Meaning
StatusUpdateEnabled | If a nonzero value, enables the port monitor to update the spooler with the port status.
StatusUpdateInterval | Specifies the interval, in seconds, when the port monitor updates the spooler with the port status.

To ensure that the spooler redirects jobs to the next available printer in the pool (when the print job is not printed within the set time), the port monitor must support SNMP (see table, following), and the network ports in the pool must be configured as "SNMP status enabled."

OS version | Port monitor that supports SNMP
Windows NT4.0 | HP Standard TCP/IP port monitor.
Windows 2000 | Standard TCP/IP port monitor

Calling SetPrinterDataEx with the pKeyName parameter set to "PrinterDriverData" is equivalent to calling the SetPrinterData function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, GetPrinterDataEx, OpenPrinter, SetPrinter, PRINTER_INFO_7


StartDoc

The StartDoc function starts a print job.

int StartDoc(
  HDC hdc,              // handle to DC
  CONST DOCINFO* lpdi   // contains file names
);

Parameters

hdc
[in] Handle to the device context for the print job.
lpdi
[in] Pointer to a DOCINFO structure containing the name of the document file and the name of the output file.

Return Values

If the function succeeds, the return value is greater than zero. This value is the print job identifier for the document.

Windows 95/98/Me: If the function succeeds, the return value is always 1.

If the function fails, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

Applications should call the StartDoc function immediately before beginning a print job. Using this function ensures that multipage documents are not interspersed with other print jobs.

Applications can use the value returned by StartDoc to retrieve or set the priority of a print job. Call the GetJob or SetJob function and supply this value as one of the required arguments.

For an example, see Printing a Document.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DOCINFO, EndDoc, GetJob, SetJob


StartDocPrinter

The StartDocPrinter function notifies the print spooler that a document is to be spooled for printing.

DWORD StartDocPrinter(
  HANDLE hPrinter,  // handle to printer object
  DWORD Level,      // information level
  LPBYTE pDocInfo   // information buffer
);

Parameters

hPrinter
[in] Handle to the printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
Level
[in] Specifies the version of the structure to which pDocInfo points.

Windows NT/Windows 2000 or later: This value must be 1.

Windows 95: This value can be 1 or 2.

pDocInfo
[in] Pointer to a structure that describes the document to print.

Windows NT/Windows 2000 or later: pDocInfo is a pointer to a DOC_INFO_1 structure.

Windows 95: pDocInfo is a pointer to a DOC_INFO_1 or a DOC_INFO_2 structure.

Return Values

If the function succeeds, the return value identifies the print job.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The return value will never be greater than 2^31 –1.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, DOC_INFO_1, DOC_INFO_2, OpenPrinter


StartPage

The StartPage function prepares the printer driver to accept data.

int StartPage(
  HDC hDC   // handle to DC
);

Parameters

hDC
[in] Handle to the device context for the print job.

Return Values

If the function succeeds, the return value is greater than zero.

If the function fails, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

The system disables the ResetDC function between calls to the StartPage and EndPage functions. This means that you cannot change the device mode except at page boundaries. After calling EndPage, you can call ResetDC to change the device mode, if necessary. Note that a call to ResetDC resets all device context attributes back to default values.

Windows 3.x: EndPage resets the device context attributes back to default values. You must re-select objects and set up the mapping mode again before printing the next page.

Windows 95: EndPage does not reset the device context attributes. However, the next StartPage call does reset the device context attributes to default values. At that time, you must re-select objects and set up the mapping mode again before printing the next page. Note that StartPage also resets the device context state stack used by the SaveDC and RestoreDC functions to default values.

Windows NT/Windows 2000 or later: Beginning with Windows NT Version 3.5, neither EndPage or StartPage resets the device context attributes. Device context attributes remain constant across subsequent pages. You do not need to re-select objects and set up the mapping mode again before printing the next page; however, doing so will produce the same results and reduce code differences between Windows and Windows NT.

For an example, see Printing a Document.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EndPage, ResetDC


StartPagePrinter

The StartPagePrinter function notifies the spooler that a page is about to be printed on the specified printer.

BOOL StartPagePrinter(
  HANDLE hPrinter   // handle to printer object
);

Parameters

hPrinter
[in] Handle to a printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When an application has finished writing a page, it should call the EndPagePrinter function to inform the spooler that the page is complete.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, EndPagePrinter, OpenPrinter


WritePrinter

The WritePrinter function notifies the print spooler that data should be written to the specified printer.

BOOL WritePrinter(
  HANDLE hPrinter,   // handle to printer object
  LPVOID pBuf,       // array of printer data
  DWORD cbBuf,       // size of array
  LPDWORD pcWritten  // bytes received
);

Parameters

hPrinter
[in] Handle to the printer. Use the OpenPrinter or AddPrinter function to retrieve a printer handle.
pBuf
[in] Pointer to an array of bytes that contains the data that should be written to the printer.
cbBuf
[in] Specifies the size, in bytes, of the array.
pcWritten
[out] Pointer to a value that receives the number of bytes of data that were written to the printer.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Library: Use Winspool.lib.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Functions, OpenPrinter


Printing and Print Spooler Structures

The following structures are used with the print spooler:

ADDJOB_INFO_1
DATATYPES_INFO_1
DEVMODE
DOC_INFO_1
DOC_INFO_2
DOC_INFO_3
DOCINFO
DRAWPATRECT
DRIVER_INFO_1
DRIVER_INFO_2
DRIVER_INFO_3
DRIVER_INFO_4
DRIVER_INFO_5
DRIVER_INFO_6
FORM_INFO_1
JOB_INFO_1
JOB_INFO_2
JOB_INFO_3
MONITOR_INFO_1
MONITOR_INFO_2
PORT_INFO_1
PORT_INFO_2
PORT_INFO_3
PRINTER_DEFAULTS
PRINTER_ENUM_VALUES
PRINTER_INFO_1
PRINTER_INFO_2
PRINTER_INFO_3
PRINTER_INFO_4
PRINTER_INFO_5
PRINTER_INFO_6
PRINTER_INFO_7
PRINTER_INFO_8
PRINTER_INFO_9
PRINTER_NOTIFY_INFO
PRINTER_NOTIFY_INFO_DATA
PRINTER_NOTIFY_OPTIONS
PRINTER_NOTIFY_OPTIONS_TYPE
PRINTPROCESSOR_CAPS_1
PRINTPROCESSOR_INFO_1
PROVIDOR_INFO_1
PROVIDOR_INFO_2
PSFEATURE_CUSTPAPER
PSFEATURE_OUTPUT
PSINJECTDATA


ADDJOB_INFO_1

The ADDJOB_INFO_1 structure identifies a print job as well as the directory and file in which an application can store that job.

typedef struct _ADDJOB_INFO_1 {
  LPTSTR  Path;
  DWORD   JobId;
} ADDJOB_INFO_1, *PADDJOB_INFO_1;

Members

Path
Pointer to a null-terminated string that contains the path and file name that the application can use to store the print job.
JobId
Handle to the print job.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddJob


DATATYPES_INFO_1

The DATATYPES_INFO_1 structure contains information about the data type used to record a print job.

typedef struct _DATATYPES_INFO_1 {
  LPTSTR pName;
} DATATYPES_INFO_1, *PDATATYPES_INFO_1;

Members

pName
Pointer to a null-terminated string that identifies the data type used to record a print job.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPrintProcessorDatatypes


DEVMODE

The DEVMODE data structure contains information about the device initialization and environment of a printer.

typedef struct _devicemode {
  BCHAR  dmDeviceName[CCHDEVICENAME];
  WORD   dmSpecVersion;
  WORD   dmDriverVersion;
  WORD   dmSize;
  WORD   dmDriverExtra;
  DWORD  dmFields;
  union {
    struct {
      short dmOrientation;
      short dmPaperSize;
      short dmPaperLength;
      short dmPaperWidth;
    };
    POINTL dmPosition;
  };
  short  dmScale;
  short  dmCopies;
  short  dmDefaultSource;
  short  dmPrintQuality;
  short  dmColor;
  short  dmDuplex;
  short  dmYResolution;
  short  dmTTOption;
  short  dmCollate;
  BCHAR  dmFormName[CCHFORMNAME];
  WORD  dmLogPixels;
  DWORD  dmBitsPerPel;
  DWORD  dmPelsWidth;
  DWORD  dmPelsHeight;
  union {
    DWORD  dmDisplayFlags;
    DWORD  dmNup;
  }
  DWORD  dmDisplayFrequency;
#if(WINVER >= 0x0400)
  DWORD  dmICMMethod;
  DWORD  dmICMIntent;
  DWORD  dmMediaType;
  DWORD  dmDitherType;
  DWORD  dmReserved1;
  DWORD  dmReserved2;
#if (WINVER >= 0x0500) || (_WIN32_WINNT >= 0x0400)
  DWORD  dmPanningWidth;
  DWORD  dmPanningHeight;
#endif
#endif /* WINVER >= 0x0400 */
} DEVMODE;

Members

dmDeviceName
Specifies the the "friendly" name of the printer; for example, "PCL/HP LaserJet" in the case of PCL/HP LaserJet®. This string is unique among device drivers. Note that this name may be truncated to fit in the dmDeviceName array.
dmSpecVersion
Specifies the version number of the initialization data specification on which the structure is based. To ensure the correct version is used for any operating system, use DM_SPECVERSION.
dmDriverVersion
Specifies the printer driver version number assigned by the printer driver developer.
dmSize
Specifies the size, in bytes, of the DEVMODE structure, not including any private driver-specific data that might follow the structure's public members. Set this member to sizeof(DEVMODE) to indicate the version of the DEVMODE structure being used.
dmDriverExtra
Contains the number of bytes of private driver-data that follow this structure. If a device driver does not use device-specific information, set this member to zero.
dmFields
Specifies whether certain members of the DEVMODE structure have been initialized. If a member is initialized, its corresponding bit is set, otherwise the bit is clear. A printer driver supports only those DEVMODE members that are appropriate for the printer technology.

The following values are defined, and are listed here with the corresponding structure members.
Value | Structure member
DM_ORIENTATION | dmOrientation
DM_PAPERSIZE | dmPaperSize
DM_PAPERLENGTH | dmPaperLength
DM_PAPERWIDTH | dmPaperWidth
DM_POSITION | dmPosition
DM_SCALE | dmScale
DM_COPIES | dmCopies
DM_DEFAULTSOURCE | dmDefaultSource
DM_PRINTQUALITY | dmPrintQuality
DM_COLOR | dmColor
DM_DUPLEX | dmDuplex
DM_YRESOLUTION | dmYResolution
DM_TTOPTION | dmTTOption
DM_COLLATE | dmCollate
DM_FORMNAME | dmFormName
DM_LOGPIXELS | dmLogPixels
DM_BITSPERPEL | dmBitsPerPel
DM_PELSWIDTH | dmPelsWidth
DM_PELSHEIGHT | dmPelsHeight
DM_DISPLAYFLAGS | dmDisplayFlags
DM_NUP | dmNup
DM_DISPLAYFREQUENCY | dmDisplayFrequency
DM_ICMMETHOD | dmICMMethod
DM_ICMINTENT | dmICMIntent
DM_MEDIATYPE | dmMediaType
DM_DITHERTYPE | dmDitherType
DM_PANNINGWIDTH | Windows 2000 or later: dmPanningWidth
DM_PANNINGHEIGHT | Windows 2000 or later: dmPanningHeight

dmOrientation
For printer devices only, selects the orientation of the paper. This member can be either DMORIENT_PORTRAIT (1) or DMORIENT_LANDSCAPE (2).
dmPaperSize
For printer devices only, selects the size of the paper to print on. This member can be set to zero if the length and width of the paper are both set by the dmPaperLength and dmPaperWidth members. Otherwise, the dmPaperSize member can be set to one of the following predefined values.
Value | Meaning
DMPAPER_LETTER | Letter, 8 1/2- by 11-inches
DMPAPER_LEGAL | Legal, 8 1/2- by 14-inches
DMPAPER_10X14 | 10- by 14-inch sheet
DMPAPER_11X17 | 11- by 17-inch sheet
DMPAPER_12X11 | Windows 98, Windows NT 4.0, and later: 12- by 11-inch sheet
DMPAPER_A3 | A3 sheet, 297- by 420-millimeters
DMPAPER_A3_ROTATED | Windows 98, Windows NT 4.0, and later: A3 rotated sheet, 420- by 297-millimeters
DMPAPER_A4 | A4 sheet, 210- by 297-millimeters
DMPAPER_A4_ROTATED | Windows 98, Windows NT 4.0 and later: A4 rotated sheet, 297- by 210-millimeters
DMPAPER_A4SMALL | A4 small sheet, 210- by 297-millimeters
DMPAPER_A5 | A5 sheet, 148- by 210-millimeters
DMPAPER_A5_ROTATED | Windows 98, Windows NT 4.0, and later: A5 rotated sheet, 210- by 148-millimeters
DMPAPER_A6 | Windows 98, Windows NT 4.0, and later: A6 sheet, 105- by 148-millimeters
DMPAPER_A6_ROTATED | Windows 98, Windows NT 4.0, and later: A6 rotated sheet, 148- by 105-millimeters
DMPAPER_B4 | B4 sheet, 250- by 354-millimeters
DMPAPER_B4_JIS_ROTATED | Windows 98, Windows NT 4.0, and later: B4 (JIS) rotated sheet, 364- by 257-millimeters
DMPAPER_B5 | B5 sheet, 182- by 257-millimeter paper
DMPAPER_B5_JIS_ROTATED | Windows 98, Windows NT 4.0, and later: B5 (JIS) rotated sheet, 257- by 182-millimeters
DMPAPER_B6_JIS | Windows 98, Windows NT 4.0, and later: B6 (JIS) sheet, 128- by 182-millimeters
DMPAPER_B6_JIS_ROTATED | Windows 98, Windows NT 4.0, and later: B6 (JIS) rotated sheet, 182- by 128-millimeters
DMPAPER_CSHEET | C Sheet, 17- by 22-inches
DMPAPER_DBL_JAPANESE_POSTCARD | Windows 98, Windows NT 4.0, and later: Double Japanese Postcard, 200- by 148-millimeters
DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED | Windows 98, Windows NT 4.0, and later: Double Japanese Postcard Rotated, 148- by 200-millimeters
DMPAPER_DSHEET | D Sheet, 22- by 34-inches
DMPAPER_ENV_9 | #9 Envelope, 3 7/8- by 8 7/8-inches
DMPAPER_ENV_10 | #10 Envelope, 4 1/8- by 9 1/2-inches
DMPAPER_ENV_11 | #11 Envelope, 4 1/2- by 10 3/8-inches
DMPAPER_ENV_12 | #12 Envelope, 4 3/4- by 11-inches
DMPAPER_ENV_14 | #14 Envelope, 5- by 11 1/2-inches
DMPAPER_ENV_C5 | C5 Envelope, 162- by 229-millimeters
DMPAPER_ENV_C3 | C3 Envelope, 324- by 458-millimeters
DMPAPER_ENV_C4 | C4 Envelope, 229- by 324-millimeters
DMPAPER_ENV_C6 | C6 Envelope, 114- by 162-millimeters
DMPAPER_ENV_C65 | C65 Envelope, 114- by 229-millimeters
DMPAPER_ENV_B4 | B4 Envelope, 250- by 353-millimeters
DMPAPER_ENV_B5 | B5 Envelope, 176- by 250-millimeters
DMPAPER_ENV_B6 | B6 Envelope, 176- by 125-millimeters
DMPAPER_ENV_DL | DL Envelope, 110- by 220-millimeters
DMPAPER_ENV_ITALY | Italy Envelope, 110- by 230-millimeters
DMPAPER_ENV_MONARCH | Monarch Envelope, 3 7/8- by 7 1/2-inches
DMPAPER_ENV_PERSONAL | 6 3/4 Envelope, 3 5/8- by 6 1/2-inches
DMPAPER_ESHEET | E Sheet, 34- by 44-inches
DMPAPER_EXECUTIVE | Executive, 7 1/4- by 10 1/2-inches
DMPAPER_FANFOLD_US | US Std Fanfold, 14 7/8- by 11-inches
DMPAPER_FANFOLD_STD_GERMAN | German Std Fanfold, 8 1/2- by 12-inches
DMPAPER_FANFOLD_LGL_GERMAN | German Legal Fanfold, 8 ½- by 13-inches
DMPAPER_FOLIO | Folio, 8 1/2- by 13-inch paper
DMPAPER_JAPANESE_POSTCARD_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Postcard Rotated, 148- by 100-millimeters
DMPAPER_JENV_CHOU3 | Windows 98, Windows NT 4.0, and later: Japanese Envelope Chou #3
DMPAPER_JENV_CHOU3_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Envelope Chou #3 Rotated
DMPAPER_JENV_CHOU4 | Windows 98, Windows NT 4.0, and later: Japanese Envelope Chou #4
DMPAPER_JENV_CHOU4_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Envelope Chou #4 Rotated
DMPAPER_JENV_KAKU2 | Windows 98, Windows NT 4.0, and later: Japanese Envelope Kaku #2
DMPAPER_JENV_KAKU2_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Envelope Kaku #2 Rotated
DMPAPER_JENV_KAKU3 | Windows 98, Windows NT 4.0, and later: Japanese Envelope Kaku #3
DMPAPER_JENV_KAKU3_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Envelope Kaku #3 Rotated
DMPAPER_JENV_YOU4 | Windows 98, Windows NT 4.0, and later: Japanese Envelope You #4
DMPAPER_JENV_YOU4_ROTATED | Windows 98, Windows NT 4.0, and later: Japanese Envelope You #4 Rotated
DMPAPER_LAST | Windows 2000 or later: DMPAPER_PENV_10_ROTATED
DMPAPER_LEDGER | Ledger, 17- by 11-inches
DMPAPER_LETTER_ROTATED | Letter Rotated 11 by 8 1/2 11 inches
DMPAPER_LETTERSMALL | Letter Small, 8 1/2- by 11-inches
DMPAPER_NOTE | Note, 8 1/2- by 11-inches
DMPAPER_P16K | Windows 98, Windows NT 4.0, and later: PRC 16K, 146- by 215-millimeters
DMPAPER_P16K_ROTATED | Windows 98, Windows NT 4.0, and later: PRC 16K Rotated, 215- by 146-millimeters
DMPAPER_P32K | Windows 98, Windows NT 4.0, and later: PRC 32K, 97- by 151-millimeters
DMPAPER_P32K_ROTATED | Windows 98, Windows NT 4.0, and later: PRC 32K Rotated, 151- by 97-millimeters
DMPAPER_P32KBIG | Windows 98, Windows NT 4.0, and later: PRC 32K(Big) 97- by 151-millimeters
DMPAPER_P32KBIG_ROTATED | Windows 98, Windows NT 4.0, and later: PRC 32K(Big) Rotated, 151- by 97-millimeters
DMPAPER_PENV_1 | Windows 98, Windows NT 4.0, and later: PRC Envelope #1, 102- by 165-millimeters
DMPAPER_PENV_1_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #1 Rotated, 165- by 102-millimeters
DMPAPER_PENV_2 | Windows 98, Windows NT 4.0, and later: PRC Envelope #2, 102- by 176-millimeters
DMPAPER_PENV_2_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #2 Rotated, 176- by 102-millimeters
DMPAPER_PENV_3 | Windows 98, Windows NT 4.0, and later: PRC Envelope #3, 125- by 176-millimeters
DMPAPER_PENV_3_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #3 Rotated, 176- by 125-millimeters
DMPAPER_PENV_4 | Windows 98, Windows NT 4.0, and later: PRC Envelope #4, 110- by 208-millimeters
DMPAPER_PENV_4_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #4 Rotated, 208- by 110-millimeters
DMPAPER_PENV_5 | Windows 98, Windows NT 4.0, and later: PRC Envelope #5, 110- by 220-millimeters
DMPAPER_PENV_5_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #5 Rotated, 220- by 110-millimeters
DMPAPER_PENV_6 | Windows 98, Windows NT 4.0, and later: PRC Envelope #6, 120- by 230-millimeters
DMPAPER_PENV_6_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #6 Rotated, 230- by 120-millimeters
DMPAPER_PENV_7 | Windows 98, Windows NT 4.0, and later: PRC Envelope #7, 160- by 230-millimeters
DMPAPER_PENV_7_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #7 Rotated, 230- by 160-millimeters
DMPAPER_PENV_8 | Windows 98, Windows NT 4.0, and later: PRC Envelope #8, 120- by 309-millimeters
DMPAPER_PENV_8_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #8 Rotated, 309- by 120-millimeters
DMPAPER_PENV_9 | Windows 98, Windows NT 4.0, and later: PRC Envelope #9, 229- by 324-millimeters
DMPAPER_PENV_9_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #9 Rotated, 324- by 229-millimeters
DMPAPER_PENV_10 | Windows 98, Windows NT 4.0, and later: PRC Envelope #10, 324- by 458-millimeters
DMPAPER_PENV_10_ROTATED | Windows 98, Windows NT 4.0, and later: PRC Envelope #10 Rotated, 458- by 324-millimeters
DMPAPER_QUARTO | Quarto, 215- by 275-millimeter paper
DMPAPER_STATEMENT | Statement, 5 1/2- by 8 1/2-inches
DMPAPER_TABLOID | Tabloid, 11- by 17-inches

dmPaperLength
For printer devices only, overrides the length of the paper specified by the dmPaperSize member, either for custom paper sizes or for devices such as dot-matrix printers that can print on a page of arbitrary length. These values, along with all other values in this structure that specify a physical length, are in tenths of a millimeter.
dmPaperWidth
For printer devices only, overrides the width of the paper specified by the dmPaperSize member.
dmPosition
Windows 98/Me, Windows 2000 or later: For display devices only, a POINTL structure that indicates the positional coordinates of the display device in reference to the desktop area. The primary display device is always located at coordinates (0,0).
dmScale
Specifies the factor by which the printed output is to be scaled. The apparent page size is scaled from the physical page size by a factor of dmScale/100. For example, a letter-sized page with a dmScale value of 50 would contain as much data as a page of 17- by 22-inches because the output text and graphics would be half their original height and width.
dmCopies
Selects the number of copies printed if the device supports multiple-page copies.
dmDefaultSource
Specifies the paper source. To retrieve a list of the available paper sources for a printer, use the DeviceCapabilities function with the DC_BINS flag.

This member can be one of the following values, or it can be a device-specific value greater than or equal to DMBIN_USER.

DMBIN_ONLYONE
DMBIN_LOWER
DMBIN_MIDDLE
DMBIN_MANUAL
DMBIN_ENVELOPE
DMBIN_ENVMANUAL
DMBIN_AUTO
DMBIN_TRACTOR
DMBIN_SMALLFMT
DMBIN_LARGEFMT
DMBIN_LARGECAPACITY
DMBIN_CASSETTE
DMBIN_FORMSOURCE

dmPrintQuality
Specifies the printer resolution. There are four predefined device-independent values:

DMRES_HIGH
DMRES_MEDIUM
DMRES_LOW
DMRES_DRAFT

If a positive value is specified, it specifies the number of dots per inch (DPI) and is therefore device dependent.

dmColor
Switches between color and monochrome on color printers. Following are the possible values:

DMCOLOR_COLOR
DMCOLOR_MONOCHROME

dmDuplex
Selects duplex or double-sided printing for printers capable of duplex printing. Following are the possible values.
Value | Meaning
DMDUP_SIMPLEX | Normal (nonduplex) printing.
DMDUP_HORIZONTAL | Short-edge binding, that is, the long edge of the page is horizontal.
DMDUP_VERTICAL | Long-edge binding, that is, the long edge of the page is vertical.

dmYResolution
Specifies the y-resolution, in dots per inch, of the printer. If the printer initializes this member, the dmPrintQuality member specifies the x-resolution, in dots per inch, of the printer.
dmTTOption
Specifies how TrueType® fonts should be printed. This member can be one of the following values.
Value | Meaning
DMTT_BITMAP | Prints TrueType fonts as graphics. This is the default action for dot-matrix printers.
DMTT_DOWNLOAD | Downloads TrueType fonts as soft fonts. This is the default action for Hewlett-Packard printers that use Printer Control Language (PCL).
DMTT_DOWNLOAD_OUTLINE | Window 95/98, Windows NT 4.0, and later: Downloads TrueType fonts as outline soft fonts.
DMTT_SUBDEV | Substitutes device fonts for TrueType fonts. This is the default action for PostScript® printers.

dmUnusedPadding
Used to align the structure to a DWORD boundary. This should not be used or referenced. Its name and usage is reserved, and can change in future releases.
dmCollate
Specifies whether collation should be used when printing multiple copies. (This member is ignored unless the printer driver indicates support for collation by setting the dmFields member to DM_COLLATE.) This member can be be one of the following values.
Value | Meaning
DMCOLLATE_TRUE | Collate when printing multiple copies.
DMCOLLATE_FALSE | Do not collate when printing multiple copies.

Using DMCOLLATE_TRUE provides faster, more efficient output for collation, since the data is sent to the device driver just once, no matter how many copies are required. The printer is told to simply print the page again.

dmFormName
Windows NT/Windows 2000 or later: Specifies the name of the form to use; for example, "Letter" or "Legal". A complete set of names can be retrieved by using the EnumForms function.

Windows 95: Printer drivers do not use this member.

dmLogPixels
Specifies the number of pixels per logical inch. Printer drivers do not use this member.
dmBitsPerPel
Specifies the color resolution, in bits per pixel, of the display device (for example: 4 bits for 16 colors, 8 bits for 256 colors, or 16 bits for 65,536 colors). Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.
dmPelsWidth
Specifies the width, in pixels, of the visible device surface. Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.
dmPelsHeight
Specifies the height, in pixels, of the visible device surface. Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.
dmDisplayFlags
Specifies the device's display mode. This member can be a combination of the following values.
Value | Meaning
DM_GRAYSCALE | Specifies that the display is a noncolor device. If this flag is not set, color is assumed.
DM_INTERLACED | Specifies that the display mode is interlaced. If the flag is not set, noninterlaced is assumed.

Display drivers use this member, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

dmNup
Specifies where the NUP is done. It can be one of the following.
Value | Meaning
DMNUP_SYSTEM | The print spooler does the NUP.
DMNUP_ONEUP | The application does the NUP.

dmDisplayFrequency
Specifies the frequency, in hertz (cycles per second), of the display device in a particular mode. This value is also known as the display device's vertical refresh rate. Display drivers use this member. It is used, for example, in the ChangeDisplaySettings function. Printer drivers do not use this member.

When you call the EnumDisplaySettings function, the dmDisplayFrequency member may return with the value 0 or 1. These values represent the display hardware's default refresh rate. This default rate is typically set by switches on a display card or computer motherboard, or by a configuration program that does not use Win32 display functions such as ChangeDisplaySettings.

dmICMMethod
Windows 95 and later; Windows 2000 or later:
Specifies how ICM is handled. For a non-ICM application, this member determines if ICM is enabled or disabled. For ICM applications, the system examines this member to determine how to handle ICM support. This member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMICMMETHOD_USER.
Value | Meaning
DMICMMETHOD_NONE | Specifies that ICM is disabled.
DMICMMETHOD_SYSTEM | Specifies that ICM is handled by Windows.
DMICMMETHOD_DRIVER | Specifies that ICM is handled by the device driver.
DMICMMETHOD_DEVICE | Specifies that ICM is handled by the destination device.

The printer driver must provide a user interface for setting this member. Most printer drivers support only the DMICMMETHOD_SYSTEM or DMICMMETHOD_NONE value. Drivers for PostScript printers support all values.

dmICMIntent
Windows 95/98, Windows 2000 or later:
Specifies which color matching method, or intent, should be used by default. This member is primarily for non-ICM applications. ICM applications can establish intents by using the ICM functions. This member can be one of the following predefined values, or a driver defined value greater than or equal to the value of DMICM_USER.
Value | Meaning
DMICM_ABS_COLORIMETRIC | Color matching should optimize to match the exact color requested without white point mapping. This value is most appropriate for use with proofing.
DMICM_COLORMETRIC | Color matching should optimize to match the exact color requested. This value is most appropriate for use with business logos or other images when an exact color match is desired.
DMICM_CONTRAST | Color matching should optimize for color contrast. This value is the most appropriate choice for scanned or photographic images when dithering is desired.
DMICM_SATURATE | Color matching should optimize for color saturation. This value is the most appropriate choice for business graphs when dithering is not desired.

dmMediaType
Windows 95/98, Windows 2000 or later:
Specifies the type of media being printed on. The member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMMEDIA_USER.
Value | Meaning
DMMEDIA_STANDARD | Plain paper.
DMMEDIA_GLOSSY | Glossy paper.
DMMEDIA_TRANSPARENCY | Transparent film.

Whistler:
To retrieve a list of the available media types for a printer, use the DeviceCapabilities function with the DC_MEDIATYPES flag.
dmDitherType
Windows 95/98, Windows 2000 or later:
Specifies how dithering is to be done. The member can be one of the following predefined values, or a driver-defined value greater than or equal to the value of DMDITHER_USER.
Value | Meaning
DMDITHER_NONE | No dithering.
DMDITHER_COARSE | Dithering with a coarse brush.
DMDITHER_FINE | Dithering with a fine brush.
DMDITHER_LINEART | Line art dithering, a special dithering method that produces well defined borders between black, white, and gray scalings. It is not suitable for images that include continuous graduations in intensisty and hue, such as scanned photographs.
DMDITHER_ERRORDIFFUSION | Windows 95/98/Me: Dithering in which an algorithm is used to spread, or diffuse, the error of approximating a specified color over adjacent pixels. In contrast, DMDITHER_COARSE, DMDITHER_FINE, and DMDITHER_LINEART use patterned halftoning to approximate a color..
DMDITHER_GRAYSCALE | Device does grayscaling.

dmReserved1
Windows 95/98, Windows 2000 or later: Not used; must be zero.
dmReserved2
Windows 95/98, Windows 2000 or later: Not used; must be zero.
dmPanningWidth
Windows NT/Windows 2000 or later: This member must be zero.

Windows 95/98/Me: This member is not supported.

dmPanningHeight
Windows NT/Windows 2000 or later: This member must be zero.

Windows 95/98/Me: This member is not supported.

Remarks

A device driver's private data follows the public portion of the DEVMODE structure. The size of the public data can vary for different versions of the structure. The dmSize member specifies the number of bytes of public data, and the dmDriverExtra member specifies the number of bytes of private data.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AdvancedDocumentProperties, ChangeDisplaySettings, CreateDC, CreateIC, DeviceCapabilities, DocumentProperties, EnumDisplaySettings, OpenPrinter


DOC_INFO_1

The DOC_INFO_1 structure describes a document that will be printed.

typedef struct _DOC_INFO_1 {
  LPTSTR pDocName;
  LPTSTR pOutputFile;
  LPTSTR pDatatype;
} DOC_INFO_1;

Members

pDocName
Pointer to a null-terminated string that specifies the name of the document.
pOutputFile
Pointer to a null-terminated string that specifies the name of an output file. To print to a printer, set this to NULL.
pDatatype
Pointer to a null-terminated string that identifies the type of data used to record the document.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, StartDocPrinter


DOC_INFO_2

The DOC_INFO_2 structure describes a document that will be printed.

typedef struct _DOC_INFO_2 {
  LPTSTR pDocName;
  LPTSTR pOutputFile;
  LPTSTR pDatatype;
  DWORD  dwMode;
  DWORD  JobId;
} DOC_INFO_2, *PDOC_INFO_2;

Members

pDocName
Pointer to a null-terminated string that specifies the name of the document.
pOutputFile
Pointer to a null-terminated string that specifies the name of an output file.
pDatatype
Pointer to a null-terminated string that identifies the type of data used to record the document.
dwMode
Informs the print spooler of the nature of the data to follow. If this value is zero, the print spooler treats the data sent by subsequent calls to WritePrinter as a normal print job (whether or not it is spooled depends on the printer property). If this value is DI_CHANNEL, only a communications channel is opened. In this case, the data passed into subsequent calls to WritePrinter is sent to the printer or subsequent calls to ReadPrinter retrieve data from the printer. This mode remains effective until EndDoc is called.
JobId
Reserved for internal use; should be zero.

Requirements

Windows NT/2000 or later: Unsupported .
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EndDoc, ReadPrinter, StartDocPrinter, WritePrinter


DOC_INFO_3

The DOC_INFO_3 structure describes a document that will be printed.

typedef struct _DOC_INFO_3 {
  LPTSTR   pDocName;
  LPTSTR   pOutputFile;
  LPTSTR   pDatatype;
  DWORD    dwFlags;
} DOC_INFO_3, *PDOC_INFO_3;

Members

pDocName
Pointer to a null-terminated string that specifies the name of the document.
pOutputFile
Pointer to a null-terminated string that specifies the name of an output file.
pDatatype
Pointer to a null-terminated string that identifies the type of data used to record the document.
dwFlags
Flags. Currently, it can be NULL or the following.
Flag | Meaning
DI_MEMORYMAP_WRITE | Causes StartDocPrinter to not use AddJob and ScheduleJob for local printing.

Remarks

The DI_MEMORYMAP_WRITE setting in DOC_INFO_3 is an optimization. This allows GDI to map spool files in the application and speed up the recording.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddJob, ScheduleJob, StartDocPrinter


DOCINFO

The DOCINFO structure contains the input and output file names and other information used by the StartDoc function.

typedef struct {
  int     cbSize;
  LPCTSTR lpszDocName;
  LPCTSTR lpszOutput;
  LPCTSTR lpszDatatype;
  DWORD   fwType;
} DOCINFO, *LPDOCINFO;

Members

cbSize
Specifies the size, in bytes, of the structure.
lpszDocName
Pointer to a null-terminated string that specifies the name of the document.
lpszOutput
Pointer to a null-terminated string that specifies the name of an output file. If this pointer is NULL, the output will be sent to the device identified by the device context handle that was passed to the StartDoc function.
lpszDatatype
Pointer to a null-terminated string that specifies the type of data, such as "raw" or "emf", used to record the print job. This member can be NULL. If it is not NULL, the StartDoc function passes it to the printer driver. Note that the printer driver might ignore the requested data type.
fwType
Specifies additional information about the print job. This member must be zero or one of the following values.
Value | Meaning
DI_APPBANDING | Applications that use banding should set this flag for optimal performance during printing.
DI_ROPS_READ_DESTINATION | The application will use raster operations that involve reading from the destination surface.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, StartDoc


DRAWPATRECT

The DRAWPATRECT structure defines a rectangle to be created.

typedef struct _DRAWPATRECT {
  POINT ptPosition;
  POINT ptSize;
  WORD wStyle;
  WORD wPattern;
} DRAWPATRECT, *PDRAWPATRECT;

Members

ptPosition
The upper-left corner of the rectangle, in logical units.
ptSize
The lower-right corner of the rectangle, in logical units.
wStyle
The style of the rectangle. It can be one of the following.
Value | Meaning
0 | Black rectangle.
1 | White rectangle.
2 | Gray rectangle. Used with wPattern.

wPattern
Amount of grayness of the rectangle, as a percentage (0-100). A value of 0 means a white rectangle and 100 means a black rectangle. This is only used when wStyle is 2.

Remarks

This structure is used with the DRAWPATTERNRECT printer escape.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, DRAWPATTERNRECT


DRIVER_INFO_1

The DRIVER_INFO_1 structure identifies a printer driver.

typedef struct _DRIVER_INFO_1 {
  LPTSTR pName;
} DRIVER_INFO_1, *PDRIVER_INFO_1;

Members

pName
Pointer to a null-terminated string that specifies the name of a printer driver.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPrinterDrivers


DRIVER_INFO_2

The DRIVER_INFO_2 structure identifies a printer driver, the driver version number, the environment for which the driver was written, the name of the file in which the driver is stored, and so on.

typedef struct _DRIVER_INFO_2 {
  DWORD  cVersion;
  LPTSTR pName;
  LPTSTR pEnvironment;
  LPTSTR pDriverPath;
  LPTSTR pDataFile;
  LPTSTR pConfigFile;
} DRIVER_INFO_2, *PDRIVER_INFO_2;

Members

cVersion
Specifies the operating system version for which the driver was written. It can be one of the following.
Value | Meaning
0 | Driver for Windows 95/98.
1 | Driver for Windows NT 3.51.
2 | Driver for Windows NT 4.0.
3 | Driver for Windows 2000.

pName
Pointer to a null-terminated string that specifies the name of the driver (for example, "QMS 810").
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the driver was written (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0").
pDriverPath
Pointer to null-terminated string that specifies a file name or full path and file name for the file that contains the device driver (for example, "c:\drivers\pscript.dll").
pDataFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains driver data (for example, "c:\drivers\Qms810.ppd").
pConfigFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device-driver's configuration .dll (for example, "c:\drivers\Pscrptui.dll").

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrinterDriver, GetPrinterDriver


DRIVER_INFO_3

The DRIVER_INFO_3 structure contains printer driver information.

typedef struct _DRIVER_INFO_3 {
  DWORD  cVersion;
  LPTSTR pName;
  LPTSTR pEnvironment;
  LPTSTR pDriverPath;
  LPTSTR pDataFile;
  LPTSTR pConfigFile;
  LPTSTR pHelpFile;
  LPTSTR pDependentFiles;
  LPTSTR pMonitorName;
  LPTSTR pDefaultDataType;
} DRIVER_INFO_3, *PDRIVER_INFO_3;

Members

cVersion
Specifies the operating system version for which the driver was written. It can be one of the following.
Value | Meaning
0 | Driver for Windows 95/98.
1 | unused
2 | Driver for Windows NT 4.0.
3 | Driver for Windows 2000.

pName
Pointer to a null-terminated string that specifies the name of the driver (for example, "QMS 810").
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the driver was written (for example, "Windows NT x86", "Windows NT R4000", "Windows NT Alpha_AXP", or "Windows 4.0").
pDriverPath
Pointer to a null-terminated string that specifies a file name or full path and file name for the file that contains the device driver (for example, "C:\DRIVERS\Pscript.dll").
pDataFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains driver data (for example, "C:\DRIVERS\Qms810.ppd").
pConfigFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's configuration dynamic-link library (for example, "C:\DRIVERS\Pscrptui.dll").
pHelpFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's help file.
pDependentFiles
Pointer to a null-terminated string that specifies the files the driver is dependent on. Each file name in the string is also terminated with a null (for example, "Pscript.dll\0Qms810.PPD\0Pscrptui.dll\0Pspcriptui.hlp\0Pstest.txt\0\0").
pMonitorName
Pointer to a null-terminated string that specifies a language monitor (for example, "PJL monitor"). This member can be NULL and should be specified only for printers capable of bidirectional communication.
pDefaultDataType
Pointer to a null-terminated string that specifies the default data type of the print job (for example, "EMF").

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrinterDriver, EnumPrinterDrivers, GetPrinterDriver


DRIVER_INFO_4

The DRIVER_INFO_4 structure contains printer driver information.

typedef struct _DRIVER_INFO_4 {
  DWORD   cVersion;
  LPTSTR     pName;
  LPTSTR     pEnvironment;
  LPTSTR     pDriverPath;
  LPTSTR     pDataFile;
  LPTSTR     pConfigFile;
  LPTSTR     pHelpFile;
  LPTSTR     pDependentFiles;
  LPTSTR     pMonitorName;
  LPTSTR     pDefaultDataType;
  LPTSTR     pszzPreviousNames;
} DRIVER_INFO_4, *PDRIVER_INFO_4;

Members

cVersion
Specifies the operating system version for which the driver was written. Currently it can only be the following.
Value | Meaning
3 | Driver for Windows 2000.

pName
Pointer to a null-terminated string that specifies the name of the driver (for example, "QMS 810").
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the driver was written (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0).
pDriverPath
Pointer to a null-terminated string that specifies a file name or full path and file name for the file that contains the device driver (for example, C:\DRIVERS\Pscript.dll).
pDataFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains driver data (for example, C:\DRIVERS\Qms810.ppd).
pConfigFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's configuration dynamic-link library (for example, C:\DRIVERS\Pscrptui.dll).
pHelpFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's help file.
pDependentFiles
Pointer to a null-terminated string that specifies the files the driver depends on. Each file name in the string is also terminated with a null (for example, Pscript.dll\0Qms810.PPD\0Pscrptui.dll\0Pspcriptui.hlp\0Pstest.txt\0\0).
pMonitorName
Pointer to a null-terminated string that specifies a language monitor (for example, PJL monitor). This member can be NULL and should be specified only for printers capable of bidirectional communication.
pDefaultDataType
Pointer to a null-terminated string that specifies the default data type of the print job (for example, EMF).
pszzPreviousNames
Pointer to a null-terminated string that specifies any previous printer driver names that are compatible with this driver (for example, OldName1\0OldName2\0\0)

Remarks

Currently pszzPreviousNames is only used during Windows 95/98 to Windows 2000 point and print.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrinterDriver, EnumPrinterDrivers, GetPrinterDriver


DRIVER_INFO_5

The DRIVER_INFO_5 structure contains printer driver information.

typedef struct _DRIVER_INFO_5 {
  DWORD   cVersion;
  LPTSTR     pName;
  LPTSTR     pEnvironment;
  LPTSTR     pDriverPath;
  LPTSTR     pDataFile;
  LPTSTR     pConfigFile;
  DWORD      dwDriverAttributes;
  DWORD      dwConfigVersion;
  DWORD      dwDriverVersion;
} DRIVER_INFO_5, *PDRIVER_INFO_5;

Members

cVersion
Specifies the operating system version for which the driver was written. Currently it can only be the following.
Value | Meaning
3 | Driver for Windows 2000.

pName
Pointer to a null-terminated string that specifies the name of the driver (for example, QMS 810).
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the driver was written (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0).
pDriverPath
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains the device driver (for example, C:\DRIVERS\Pscript.dll).
pDataFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains driver data (for example, C:\DRIVERS\Qms810.ppd).
pConfigFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's configuration dynamic-link library (for example, C:\DRIVERS\Pscrptui.dll).
dwDriverAttributes
Driver attributes, like UMPD/KMPD.
dwConfigVersion
Version number of the configuration file since restart.
dwDriverVersion
Version number of the driver since restart.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrinterDriver, EnumPrinterDrivers, GetPrinterDriver


DRIVER_INFO_6

The DRIVER_INFO_6 structure contains printer driver information.

typedef struct _DRIVER_INFO_6 {
  DWORD   cVersion;
  LPTSTR     pName;                // QMS 810
  LPTSTR     pEnvironment;         // Win32 x86
  LPTSTR     pDriverPath;          // c:\drivers\pscript.dll
  LPTSTR     pDataFile;            // c:\drivers\QMS810.PPD
  LPTSTR     pConfigFile;         // c:\drivers\PSCRPTUI.DLL
  LPTSTR     pHelpFile;           // c:\drivers\PSCRPTUI.HLP
  LPTSTR     pDependentFiles;     // several files
  LPTSTR     pMonitorName;        // "PJL monitor"
  LPTSTR     pDefaultDataType;    // "EMF"
  LPTSTR     pszzPreviousNames;   // "OldName1\0OldName2\0\0
  FILETIME   ftDriverDate;
  DWORDLONG  dwlDriverVersion;
  LPTSTR     pszMfgName;
  LPTSTR     pszOEMUrl;
  LPTSTR     pszHardwareID;
  LPTSTR     pszProvider;
} DRIVER_INFO_6, *PDRIVER_INFO_6, *LPDRIVER_INFO_6;

Members

cVersion
Specifies the operating system version for which the driver was written. Currently it can be the following.
Value | Meaning
3 | Driver for Windows 2000.

pName
Pointer to a null-terminated string that specifies the name of the driver (for example, QMS 810).
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the driver was written (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0).
pDriverPath
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains the device driver (for example, C:\DRIVERS\Pscript.dll).
pDataFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the file that contains driver data (for example, C:\DRIVERS\Qms810.ppd).
pConfigFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's configuration dynamic-link library (for example, C:\DRIVERS\Pscrptui.dll).
pHelpFile
Pointer to a null-terminated string that specifies a file name or a full path and file name for the device driver's help file (for example, C:\DRIVERS\Pscrptui.hlp).
pDependentFiles
Pointer to a null-terminated string that specifies the files the driver depends on. Each file name is separated by a backslash and a null character (for example, Pscript.dll\0QMS810.ppd\0Pscriptui.dll\0Pscriptui.hlp\0Pstest.txt\0\0).
pMonitorName
Pointer to a null-terminated string that specifies a language monitor (for example, "PJL monitor"). This member can be NULL and should be specified only for printers capable of bidirectional communication.
pDefaultDataType
Pointer to a null-terminated string that specifies the default data type of the print job (for example, "EMF").
pszzPreviousNames
Pointer to a null-terminated string that specifies any previous printer driver names that are compatible with this driver (for example, OldName1\0OldName2\0\0).
ftDriverDate
The date of the driver package, as coded in the driver files.
dwlDriverVersion
Version number of the driver. This comes out of the version structure of the driver.
pszMfgName
Pointer to a null-terminated string that specifies the manufacturer's name.
pszOEMUrl
Pointer to a null-terminated string that specifies the URL for the manufacturer.
pszHardwareID
Pointer to a null-terminated string that specifies the hardware ID for the printer driver.
pszProvider
Pointer to a null-terminated string that specifies the provider of the printer driver (for example, "Microsoft Windows 2000")

Remarks

The strings for these members are contained in the .inf file that is used to add the driver.

Currently pszzPreviousNames is only used during Windows 95/98/Me to Windows 2000 point and print.

If you call AddPrinterDriver or AddPrinterDriverEx with Level not equal to 6, and then you call GetPrinterDriver or EnumPrinterDrivers with Level equal to 6, the DRIVER_INFO_6 structure is returned with pszMfgName, pszOEMUrl, pszHardwareID, and pszProvider set to NULL, dwlDriverVersion set to 0, and ftDriverDate set to (0,0).

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows Me.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrinterDriver, AddPrinterDriverEx, EnumPrinterDrivers, GetPrinterDriver


FORM_INFO_1

The FORM_INFO_1 structure contains information about a print form. The information includes the print form's origin, its name, its dimensions, and the dimensions of its printable area.

typedef struct _FORM_INFO_1 {
  DWORD Flags;
  LPTSTR pName;
  SIZEL  Size;
  RECTL  ImageableArea;
} FORM_INFO_1, *PFORM_INFO_1;

Members

Flags
Specifies the form properties. The following values are defined.
Value | Meaning
FORM_USER | If this bit flag is set, the form has been defined by the user. Forms with this flag set are defined in the registry.
FORM_BUILTIN | If this bit-flag is set, the form is part of the spooler. Form definitions with this flag set do not appear in the registry.
FORM_PRINTER | If this bit flag is set, the form is associated with a certain printer, and its definition appears in the registry.

pName
Pointer to a null-terminated string that specifies the name of the form.
Size
Specifies the width and height, in thousandths of millimeters, of the form.
ImageableArea
Specifies the width and height, in thousandths of millimeters, of the form.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddForm, GetForm, SetForm


JOB_INFO_1

The JOB_INFO_1 structure specifies print-job information such as the job-identifier value, the name of the printer for which the job is spooled, the name of the machine that created the print job, the name of the user that owns the print job, and so on.

typedef struct _JOB_INFO_1 {
  DWORD  JobId;
  LPTSTR pPrinterName;
  LPTSTR pMachineName;
  LPTSTR pUserName;
  LPTSTR pDocument;
  LPTSTR pDatatype;
  LPTSTR pStatus;
  DWORD  Status;
  DWORD  Priority;
  DWORD  Position;
  DWORD  TotalPages;
  DWORD  PagesPrinted;
  SYSTEMTIME Submitted;
} JOB_INFO_1, *PJOB_INFO_1;

Members

JobId
Specifies a job identifier.
pPrinterName
Pointer to a null-terminated string that specifies the name of the printer for which the job is spooled.
pMachineName
Pointer to a null-terminated string that specifies the name of the machine that created the print job.
pUserName
Pointer to a null-terminated string that specifies the name of the user that owns the print job.
pDocument
Pointer to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").
pDatatype
Pointer to a null-terminated string that specifies the type of data used to record the print job.
pStatus
Pointer to a null-terminated string that specifies the status of the print job. This member should be checked prior to Status and, if pStatus is NULL, the status is defined by the contents of the Status member.
Status
Specifies the job status. This member can be one or more of the following values.
Value | Meaning
JOB_STATUS_BLOCKED_DEVQ | The driver cannot print the job.
JOB_STATUS_COMPLETE | Whistler: Job is sent to the printer, but the job may not be printed yet. See Remarks for more information.
JOB_STATUS_DELETED | Job has been deleted.
JOB_STATUS_DELETING | Job is being deleted.
JOB_STATUS_ERROR | An error is associated with the job.
JOB_STATUS_OFFLINE | Printer is offline.
JOB_STATUS_PAPEROUT | Printer is out of paper.
JOB_STATUS_PAUSED | Job is paused.
JOB_STATUS_PRINTED | Job has printed.
JOB_STATUS_PRINTING | Job is printing.
JOB_STATUS_RESTART | Job has been restarted.
JOB_STATUS_SPOOLING | Job is spooling.
JOB_STATUS_USER_INTERVENTION | Printer has an error that requires the user to do something.

Priority
Specifies the job priority. This member can be one of the following values or in the range between 1 through 99 (MIN_PRIORITY through MAX_PRIORITY).
Value | Meaning
MIN_PRIORITY | Minimum priority.
MAX_PRIORITY | Maximum priority.
DEF_PRIORITY | Default priority.

Position
Specifies the job's position in the print queue.
TotalPages
Specifies how many pages the document contains. This value may be zero if the print job does not contain page delimiting information.
PagesPrinted
Specifies the number of pages that have printed. This value may be zero if the print job does not contain page delimiting information.
Submitted
A SYSTEMTIME structure that specifies the time that this document was spooled.

This time value is in Universal Time Coordinate (UTC) format. You should convert it to a local time value before displaying it. You can use the FileTimeToLocalFileTime function to perform the conversion.

Remarks

Whistler: Port monitors that do not support TrueEndOfJob will set the job as JOB_STATUS_PRINTED right after the job is submitted to the printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumJobs, GetJob, SetJob, SYSTEMTIME


JOB_INFO_2

The JOB_INFO_2 structure describes a full set of values associated with a job.

typedef struct _JOB_INFO_2 {
  DWORD      JobId;
  LPTSTR     pPrinterName;
  LPTSTR     pMachineName;
  LPTSTR     pUserName;
  LPTSTR     pDocument;
  LPTSTR     pNotifyName;
  LPTSTR     pDatatype;
  LPTSTR     pPrintProcessor;
  LPTSTR     pParameters;
  LPTSTR     pDriverName;
  LPDEVMODE  pDevMode;
  LPTSTR     pStatus;
  PSECURITY_DESCRIPTOR pSecurityDescriptor;
  DWORD      Status;
  DWORD      Priority;
  DWORD      Position;
  DWORD      StartTime;
  DWORD      UntilTime;
  DWORD      TotalPages;
  DWORD      Size;
  SYSTEMTIME Submitted;
  DWORD      Time;
  DWORD      PagesPrinted;
} JOB_INFO_2, *PJOB_INFO_2;

Members

JobId
Specifies a job identifier value.
pPrinterName
Pointer to a null-terminated string that specifies the name of the printer for which the job is spooled.
pMachineName
Pointer to a null-terminated string that specifies the name of the machine that created the print job.
pUserName
Pointer to a null-terminated string that specifies the name of the user who owns the print job.
pDocument
Pointer to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").
pNotifyName
Pointer to a null-terminated string that specifies the name of the user who should be notified when the job has been printed or when an error occurs while printing the job.
pDatatype
Pointer to a null-terminated string that specifies the type of data used to record the print job.
pPrintProcessor
Pointer to a null-terminated string that specifies the name of the print processor that should be used to print the job.
pParameters
Pointer to a null-terminated string that specifies print-processor parameters.
pDriverName
Pointer to a null-terminated string that specifies the name of the printer driver that should be used to process the print job.
pDevMode
Pointer to a DEVMODE structure that contains device-initialization and environment data for the printer driver.
pStatus
Pointer to a null-terminated string that specifies the status of the print job. This member should be checked prior to Status and, if pStatus is NULL, the status is defined by the contents of the Status member.
pSecurityDescriptor
The value of this member is NULL. Retrieval and setting of document security descriptors is not supported in this release.
Status
Specifies the job status. This member can be one or more of the following values.
Value | Meaning
JOB_STATUS_BLOCKED_DEVQ | The driver cannot print the job.
JOB_STATUS_COMPLETE | Whistler: Job is sent to the printer, but the job may not be printed yet. See Remarks for more information.
JOB_STATUS_DELETED | Job has been deleted.
JOB_STATUS_DELETING | Job is being deleted.
JOB_STATUS_ERROR | An error is associated with the job.
JOB_STATUS_OFFLINE | Printer is offline.
JOB_STATUS_PAPEROUT | Printer is out of paper.
JOB_STATUS_PAUSED | Job is paused.
JOB_STATUS_PRINTED | Job has printed.
JOB_STATUS_PRINTING | Job is printing.
JOB_STATUS_RESTART | Job has been restarted.
JOB_STATUS_SPOOLING | Job is spooling.
JOB_STATUS_USER_INTERVENTION | Printer has an error that requires the user to do something.

Priority
Specifies the job priority. This member can be one of the following values or in the range between 1 through 99 (MIN_PRIORITY through MAX_PRIORITY).
Value | Meaning
MIN_PRIORITY | Minimum priority.
MAX_PRIORITY | Maximum priority.
DEF_PRIORITY | Default priority.

Position
Specifies the job's position in the print queue.
StartTime
Specifies the earliest time that the job can be printed.
UntilTime
Specifies the the latest time that the job can be printed.
TotalPages
Specifies the number of pages required for the job. This value may be zero if the print job does not contain page delimiting information.
Size
Specifies the size, in bytes, of the job.
Submitted
A SYSTEMTIME structure that specifies the time when the job was submitted.

This time value is in Universal Time Coordinate (UTC) format. You should convert it to a local time value before displaying it. You can use the FileTimeToLocalFileTime function to perform the conversion.

Time
Specifies the total time, in milliseconds, that has elapsed since the job began printing.
PagesPrinted
Specifies the number of pages that have printed. This value may be zero if the print job does not contain page delimiting information.

Remarks

Whistler: Port monitors that do not support TrueEndOfJob will set the job as JOB_STATUS_PRINTED right after the job is submitted to the printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, DEVMODE, EnumJobs, GetJob, SetJob, SYSTEMTIME


JOB_INFO_3

The JOB_INFO_3 structure is used to link together a set of print jobs.

typedef struct _JOB_INFO_3 {
  DWORD      JobId;
  DWORD      NextJobId;
  DWORD      Reserved;
} JOB_INFO_3, *PJOB_INFO_3;

Members

JobId
Print job identifer.
NextJobId
Print job identifier for the next print job in the linked set of print jobs.
Reserved
This value is reserved for future use. You must set it to zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumJobs, GetJob, SetJob


MONITOR_INFO_1

The MONITOR_INFO_1 structure identifies an installed monitor.

typedef struct _MONITOR_INFO_1 {
  LPTSTR pName;
} MONITOR_INFO_1, *PMONITOR_INFO_1;

Members

pName
Pointer to a null-terminated string that identifies an installed monitor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumMonitors, MONITOR_INFO_2


MONITOR_INFO_2

The MONITOR_INFO_2 structure identifies a monitor.

typedef struct _MONITOR_INFO_2 {
  LPTSTR pName;
  LPTSTR pEnvironment;
  LPTSTR pDLLName;
} MONITOR_INFO_2, *PMONITOR_INFO_2;

Members

pName
Pointer to a null-terminated string that is the name of the monitor.
pEnvironment
Pointer to a null-terminated string that specifies the environment for which the monitor was written (for example, Windows NT x86, Windows NT R4000, Windows NT Alpha_AXP, or Windows 4.0).
pDLLName
Pointer to a null-terminated string that is the name of the monitor DLL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddMonitor, EnumMonitors, MONITOR_INFO_1


PORT_INFO_1

The PORT_INFO_1 structure identifies a supported printer port.

typedef struct _PORT_INFO_1 {
  LPTSTR pName;
} PORT_INFO_1, *PPORT_INFO_1;

Members

pName
Pointer to a null-terminated string that identifies a supported printer port (for example, "LPT1:").

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPorts


PORT_INFO_2

The PORT_INFO_2 structure identifies a supported printer port.

typedef struct _PORT_INFO_2 {
  LPTSTR pPortName;
  LPTSTR pMonitorName
  LPTSTR pDescription;
  DWORD fPortType;
  DWORD Reserved;
} PORT_INFO_2, *PPORT_INFO_2;

Members

pPortName
Pointer to a null-terminated string that identifies a supported printer port (for example, "LPT1:").
pMonitorName
Pointer to a null-terminated string that identifies an installed monitor (for example, "PJL monitor").
pDescription
Pointer to a null-terminated string that describes the port in more detail (for example, if pPortName is "LPT1:", pDescription is "printer port").
fPortType
Bitmask describing the type of port. This member can be a combination of the following values:

PORT_TYPE_WRITE
PORT_TYPE_READ
PORT_TYPE_REDIRECTED
PORT_TYPE_NET_ATTACHED

Reserved
Reserved; must be zero.

Remarks

Use the PORT_INFO_2 structure when calling EnumPorts if there are multiple monitors installed that support the same ports.

Windows 2000 or later: The fPortType field can be queried to determine information about the port. Note that on Windows 2000, port settings do not influence printer attributes (as returned by the Attributes member of PRINTER_INFO_2).

Windows 95/98/Me: The fPortType field does influence printer attributes. If fPortType is set to PORT_TYPE_REDIRECTED or PORT_TYPE_NET_ATTACHED, any printer attached to the port will appear as a network printer. In addition, if the PORT_TYPE_REDIRECTED bit is set then offline printing semantics are used for any printer attached to the port.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPorts


PORT_INFO_3

The PORT_INFO_3 structure specifies the status value of a printer port.

typedef struct _PORT_INFO_3 {
  DWORD dwStatus;
  LPTSTR pszStatus;
  DWORD dwSeverity;
} PORT_INFO_3, *PPORT_INFO_3;

Members

dwStatus
Specifies the new port status value. This value is used only if the pszStatus member is NULL.

This member can be any reasonable comination of the following values.
Value | Meaning
0 | Clears the printer port status.
PORT_STATUS_OFFLINE | The port's printer is offline.
PORT_STATUS_PAPER_JAM | The port's printer has a paper jam.
PORT_STATUS_PAPER_OUT | The port's printer is out of paper.
PORT_STATUS_OUTPUT_BIN_FULL | The port's printer's output bin is full.
PORT_STATUS_PAPER_PROBLEM | The port's printer has a paper problem.
PORT_STATUS_NO_TONER | The port's printer is out of toner.
PORT_STATUS_DOOR_OPEN | The door of the port's printer is open.
PORT_STATUS_OUT_OF_MEMORY | The port's printer is out of memory.
PORT_STATUS_TONER_LOW | The port's printer is low on toner.
PORT_STATUS_WARMING_UP | The port's printer is warming up.
PORT_STATUS_POWER_SAVE | The port's printer is in a power-conservation mode.

pszStatus
Pointer to a new printer port status value string to set. Use this member if there is no suitable status value among those listed for dwStatus.
dwSeverity
Specifies the severity of the port status value.

This member can be one of the following values.
Value | Meaning
PORT_STATUS_TYPE_ERROR | The port status value indicates an error.
PORT_STATUS_TYPE_WARNING | The port status value is a warning.
PORT_STATUS_TYPE_INFO | The port status value is informational.

Remarks

When you set a printer port status value with the severity value PORT_STATUS_TYPE_ERROR, the print spooler stops sending jobs to the port. The print spooler does not resume sending jobs to the port until another SetPort call is made to clear the status.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, SetPort


PRINTER_DEFAULTS

The PRINTER_DEFAULTS structure specifies the default data type, environment, initialization data, and access rights for a printer.

typedef struct _PRINTER_DEFAULTS {
  LPTSTR      pDatatype;
  LPDEVMODE   pDevMode;
  ACCESS_MASK DesiredAccess;
} PRINTER_DEFAULTS, *PPRINTER_DEFAULTS;

Members

pDatatype
Pointer to a null-terminated string that specifies the default data type for a printer.
pDevMode
Pointer to a DEVMODE structure that identifies the default environment and initialization data for a printer.
DesiredAccess
Windows NT/Windows 2000 or later: Specifies desired access rights for a printer. The OpenPrinter function uses this member to set access rights to the printer. These rights can affect the operation of the SetPrinter and DeletePrinter functions. The access rights can be one of the following.
Value | Meaning
PRINTER_ACCESS_ADMINISTER | To perform administrative tasks, such as those provided by SetPrinter.
PRINTER_ACCESS_USE | To perform basic printing operations.
PRINTER_ALL_ACCESS | To perform all administrative tasks and basic printing operations except for SYNCHRONIZE (see Standard Access Rights.
generic security values, such as WRITE_DAC | To allow specific control access rights. See Standard Access Rights.

Windows 95/98/Me: This member is ignored.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, DeletePrinter, DEVMODE, OpenPrinter, SetPrinter


PRINTER_ENUM_VALUES

The PRINTER_ENUM_VALUES structure specifies the value name, type, and data for a printer configuration value returned by the EnumPrinterDataEx function.

typedef struct _PRINTER_ENUM_VALUES {
  LPTSTR   pValueName;
  DWORD   cbValueName;
  DWORD   dwType;
  LPBYTE  pData;
  DWORD   cbData;
} PRINTER_ENUM_VALUES, *PPRINTER_ENUM_VALUES;

Members

pValueName
Pointer to a null-terminated string that specifies the name of the retrieved value.
cbValueName
Specifies the number of bytes in pValueName, including the terminating NULL character.
dwType
Specifies a code indicating the type of data pointed to by the pData member. For a list of the possible type codes, see Registry Value Types.
pData
Pointer to a buffer containing the data for the retrieved value.
cbData
Specifies the number of bytes retrieved in the pData buffer.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPrinterDataEx


PRINTER_INFO_1

The PRINTER_INFO_1 structure specifies general printer information.

typedef struct _PRINTER_INFO_1 {
  DWORD  Flags;
  LPTSTR pDescription;
  LPTSTR pName;
  LPTSTR pComment;
} PRINTER_INFO_1, *PPRINTER_INFO_1;

Members

Flags
Specifies information about the returned data. Following are the values for this member.
Value | Meaning
PRINTER_ENUM_EXPAND | A print provider can set this flag as a hint to a calling application to enumerate this object further if default expansion is enabled. For example, when domains are enumerated, a print provider might indicate the user's domain by setting this flag.
PRINTER_ENUM_CONTAINER | If this flag is set, the printer object may contain enumerable objects. For example, the object may be a print server that contains printers.
PRINTER_ENUM_ICON1 | Indicates that, where appropriate, an application should display an icon identifying the object as a top-level network name, such as Microsoft Windows Network.
PRINTER_ENUM_ICON2 | Indicates that, where appropriate, an application should display an icon that identifies the object as a network domain.
PRINTER_ENUM_ICON3 | Indicates that, where appropriate, an application should display an icon that identifies the object as a print server.
PRINTER_ENUM_ICON4 | Reserved for future use.
PRINTER_ENUM_ICON5 | Reserved for future use.
PRINTER_ENUM_ICON6 | Reserved for future use.
PRINTER_ENUM_ICON7 | Reserved for future use.
PRINTER_ENUM_ICON8 | Indicates that, where appropriate, an application should display an icon that identifies the object as a printer.

pDescription
Windows NT/Windows 2000 or later: Pointer to a null-terminated string that describes the contents of the structure.

Windows 95: Pointer to a null-terminated string that describes the printer. The string contains the pPrinterName, pDriverName, and pComment members of the PRINTER_INFO_2 structure concatenated and separated by commas.

pName
Windows NT/Windows 2000 or later: Pointer to a null-terminated string that names the contents of the structure.

Windows 95: Pointer to a null-terminated string that specifies the name of the printer.

pComment
Windows NT/Windows 2000 or later: Pointer to a null-terminated string that contains additional data describing the structure.

Windows 95: Pointer to a null-terminated string that provides a brief description of the printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GetPrinter, EnumPrinters, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4


PRINTER_INFO_2

The PRINTER_INFO_2 structure specifies detailed printer information.

typedef struct _PRINTER_INFO_2 {
  LPTSTR    pServerName;
  LPTSTR    pPrinterName;
  LPTSTR    pShareName;
  LPTSTR    pPortName;
  LPTSTR    pDriverName;
  LPTSTR    pComment;
  LPTSTR    pLocation;
  LPDEVMODE pDevMode;
  LPTSTR    pSepFile;
  LPTSTR    pPrintProcessor;
  LPTSTR    pDatatype;
  LPTSTR    pParameters;
  PSECURITY_DESCRIPTOR pSecurityDescriptor;
  DWORD     Attributes;
  DWORD     Priority;
  DWORD     DefaultPriority;
  DWORD     StartTime;
  DWORD     UntilTime;
  DWORD     Status;
  DWORD     cJobs;
  DWORD     AveragePPM;
} PRINTER_INFO_2, *PPRINTER_INFO_2;

Members

pServerName
Pointer to a null-terminated string identifying the server that controls the printer. If this string is NULL, the printer is controlled locally.
pPrinterName
Pointer to a null-terminated string that specifies the name of the printer.
pShareName
Pointer to a null-terminated string that identifies the sharepoint for the printer. (This string is used only if the PRINTER_ATTRIBUTE_SHARED constant was set for the Attributes member.)
pPortName
Pointer to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port must be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

Windows 95: This member can specify only one port because multiple ports per printer are not supported.

pDriverName
Pointer to a null-terminated string that specifies the name of the printer driver.
pComment
Pointer to a null-terminated string that provides a brief description of the printer.
pLocation
Pointer to a null-terminated string that specifies the physical location of the printer (for example, "Bldg. 38, Room 1164").
pDevMode
Pointer to a DEVMODE structure that defines default printer data such as the paper orientation and the resolution.
pSepFile
Pointer to a null-terminated string that specifies the name of the file used to create the separator page. This page is used to separate print jobs sent to the printer.
pPrintProcessor
Pointer to a null-terminated string that specifies the name of the print processor used by the printer. You can use the EnumPrintProcessors function to obtain a list of print processors installed on a server.
pDatatype
Pointer to a null-terminated string that specifies the data type used to record the print job. You can use the EnumPrintProcessorDatatypes function to obtain a list of data types supported by a specific print processor.
pParameters
Pointer to a null-terminated string that specifies the default print-processor parameters.
pSecurityDescriptor
Pointer to a SECURITY_DESCRIPTOR structure for the printer. This member may be NULL.

Windows 95: This member is ignored.

Attributes
Specifies the printer attributes. This member can be any reasonable combination of the following values.
Value | Meaning
PRINTER_ATTRIBUTE_DEFAULT | Windows 95: Indicates the printer is the default printer in the system.
PRINTER_ATTRIBUTE_DIRECT | Job is sent directly to the printer (it is not spooled).
PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST | If set and printer is set for print-while-spooling, any jobs that have completed spooling are scheduled to print before jobs that have not completed spooling.
PRINTER_ATTRIBUTE_ENABLE_BIDI | Windows 95: Indicates whether bi-directional communications are enabled for the printer.
PRINTER_ATTRIBUTE_ENABLE_DEVQ | If set, DevQueryPrint is called. DevQueryPrint may fail if the document and printer setups do not match. Setting this flag causes mismatched documents to be held in the queue.
PRINTER_ATTRIBUTE_FAX | Whistler: If set, printer is a fax printer. This can only be set by AddPrinter, but it can be retrieved by EnumPrinters and GetPrinter.
PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS | If set, jobs are kept after they are printed. If unset, jobs are deleted.
PRINTER_ATTRIBUTE_QUEUED | If set, the printer spools and starts printing after the last page is spooled. If not set and PRINTER_ATTRIBUTE_DIRECT is not set, the printer spools and prints while spooling.
PRINTER_ATTRIBUTE_SHARED | Printer is shared.
PRINTER_ATTRIBUTE_WORK_OFFLINE | Windows 95: Indicates whether the printer is currently connected. If the printer is not currently connected, print jobs will continue to spool.
PRINTER_ATTRIBUTE_PUBLISHED | Windows 2000 or later: Indicates whether the printer is published in the directory service.
PRINTER_ATTRIBUTE_NETWORK | Printer is a network printer connection.
PRINTER_ATTRIBUTE_HIDDEN | Reserved.
PRINTER_ATTRIBUTE_LOCAL | Printer is a local printer.
PRINTER_ATTRIBUTE_RAW_ONLY | Indicates that only raw data type print jobs can be spooled.

Priority
Specifies a priority value that the spooler uses to route print jobs.
DefaultPriority
Specifies the default priority value assigned to each print job.
StartTime
Specifies the earliest time at which the printer will print a job. This value is expressed as minutes elapsed since 12:00 AM GMT (Greenwich Mean Time).
UntilTime
Specifies the latest time at which the printer will print a job. This value is expressed as minutes elapsed since 12:00 AM GMT (Greenwich Mean Time).
Status
Specifies the printer status. This member can be any reasonable combination of the following values.
Value | Meaning
PRINTER_STATUS_BUSY | The printer is busy.
PRINTER_STATUS_DOOR_OPEN | The printer door is open.
PRINTER_STATUS_ERROR | The printer is in an error state.
PRINTER_STATUS_INITIALIZING | The printer is initializing.
PRINTER_STATUS_IO_ACTIVE | The printer is in an active input/output state
PRINTER_STATUS_MANUAL_FEED | The printer is in a manual feed state.
PRINTER_STATUS_NO_TONER | The printer is out of toner.
PRINTER_STATUS_NOT_AVAILABLE | The printer is not available for printing.
PRINTER_STATUS_OFFLINE | The printer is offline.
PRINTER_STATUS_OUT_OF_MEMORY | The printer has run out of memory.
PRINTER_STATUS_OUTPUT_BIN_FULL | The printer's output bin is full.
PRINTER_STATUS_PAGE_PUNT The printer cannot print the current page.

Windows 95: Indicates the page is being "punted" (that is, not printed) because it is too complex for the printer to print.

PRINTER_STATUS_PAPER_JAM | Paper is jammed in the printer
PRINTER_STATUS_PAPER_OUT | The printer is out of paper.
PRINTER_STATUS_PAPER_PROBLEM | The printer has a paper problem.
PRINTER_STATUS_PAUSED | The printer is paused.
PRINTER_STATUS_PENDING_DELETION | The printer is deleting a print job.
PRINTER_STATUS_POWER_SAVE | The printer is in power save mode.
PRINTER_STATUS_PRINTING | The printer is printing.
PRINTER_STATUS_PROCESSING | The printer is processing a print job.
PRINTER_STATUS_SERVER_UNKNOWN | The printer status is unknown.
PRINTER_STATUS_TONER_LOW | The printer is low on toner.
PRINTER_STATUS_USER_INTERVENTION | The printer has an error that requires the user to do something.
PRINTER_STATUS_WAITING | The printer is waiting.
PRINTER_STATUS_WARMING_UP | The printer is warming up.

cJobs
Specifies the number of print jobs that have been queued for the printer.
AveragePPM
Specifies the average number of pages per minute that have been printed on the printer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, DEVMODE, EnumPrinters, PRINTER_INFO_1, PRINTER_INFO_3, PRINTER_INFO_4, SECURITY_DESCRIPTOR


PRINTER_INFO_3

The PRINTER_INFO_3 structure specifies printer security information.

typedef struct _PRINTER_INFO_3 {
  PSECURITY_DESCRIPTOR pSecurityDescriptor;
} PRINTER_INFO_3, *PPRINTER_INFO_3;

Members

pSecurityDescriptor
Pointer to a SECURITY_DESCRIPTOR structure that specifies a printer's security information.

Remarks

The PRINTER_INFO_3 structure lets an application get and set a printer's security descriptor. The caller may do so even if it lacks specific printer permissions, as long as it has the standard rights described in SetPrinter and GetPrinter. Thus, an application may temporarily deny all access to a printer, while allowing the owner of the printer to have access to the printer's discretionary ACL.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, SetPrinter, GetPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_4, SECURITY_DESCRIPTOR


PRINTER_INFO_4

The PRINTER_INFO_4 structure specifies general printer information.

The structure can be used to retrieve minimal printer information on a call to EnumPrinters. Such a call is a fast and easy way to retrieve the names and attributes of all locally installed printers on a system and all remote printer connections that a user has established.

typedef struct _PRINTER_INFO_4 {
  LPTSTR  pPrinterName;
  LPTSTR  pServerName;
  DWORD  Attributes;
} PRINTER_INFO_4, *PPRINTER_INFO_4;

Members

pPrinterName
Pointer to a null-terminated string that specifies the name of the printer (local or remote).
pServerName
Pointer to a null-terminated string that is the name of the server.
Attributes
Specifies information about the returned data.
Value | Meaning
PRINTER_ATTRIBUTE_LOCAL | The printer is a local printer.
PRINTER_ATTRIBUTE_NETWORK | The printer is a remote printer.

Remarks

The PRINTER_INFO_4 structure provides an easy and extremely fast way to retrieve the names of the printers installed on a local machine, as well as the remote connections that a user has established. When EnumPrinters is called with a PRINTER_INFO_4 data structure, that function queries the registry for the specified information, then returns immediately. This differs from the behavior of EnumPrinters when called with other levels of PRINTER_INFO_xxx data structures. In particular, when EnumPrinters is called with a level 2 (PRINTER_INFO_2) data structure, it performs an OpenPrinter call on each remote connection. If a remote connection is down, if the remote server no longer exists, or if the remote printer no longer exists, the function must wait for RPC to time out and consequently fail the OpenPrinter call. This can take a while. Passing a PRINTER_INFO_4 structure lets an application retrieve a bare minimium of required information; if more detailed information is desired, a subsequent EnumPrinter level 2 call can be made.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GetPrinter, EnumPrinters, OpenPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3


PRINTER_INFO_5

The PRINTER_INFO_5 structure specifies detailed printer information.

typedef struct _PRINTER_INFO_5 {
  LPTSTR    pPrinterName;
  LPTSTR    pPortName;
  DWORD     Attributes;
  DWORD     DeviceNotSelectedTimeout;
  DWORD     TransmissionRetryTimeout;
} PRINTER_INFO_5, *PPRINTER_INFO_5;

Members

pPrinterName
Pointer to a null-terminated string that specifies the name of the printer.
pPortName
Pointer to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port must be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

Windows 95: This member can specify only one port because multiple ports per printer are not supported.

Attributes
Specifies the printer attributes. This member can be any reasonable combination of the following values.
Value | Meaning
PRINTER_ATTRIBUTE_DEFAULT | Windows 95: Indicates the printer is the default printer in the system.
PRINTER_ATTRIBUTE_DIRECT | Job is sent directly to printer (it is not spooled).
PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST | If set and printer is set for print-while-spooling, any jobs that have completed spooling are scheduled to print before jobs that have not completed spooling.
PRINTER_ATTRIBUTE_ENABLE_BIDI | Windows 95: Indicates whether bidirectional communications are enabled for the printer.
PRINTER_ATTRIBUTE_ENABLE_DEVQ | If set, DevQueryPrint is called. DevQueryPrint may fail if the document and printer setups do not match. Setting this flag causes mismatched documents to be held in the queue.
PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS | If set, jobs are kept after they have printed. If unset, jobs are deleted.
PRINTER_ATTRIBUTE_QUEUED | If set, the printer spools and starts printing after the last page is spooled. If not set and PRINTER_ATTRIBUTE_DIRECT is not set, the printer spools and prints while spooling.
PRINTER_ATTRIBUTE_SHARED | Printer is shared.
PRINTER_ATTRIBUTE_WORK_OFFLINE | Windows 95: Indicates whether the printer is currently connected. If the printer is not currently connected, print jobs will continue to spool.
PRINTER_ATTRIBUTE_PUBLISHED | Windows 2000 or later: Indicates whether the printer is published in the directory service.
PRINTER_ATTRIBUTE_NETWORK | Printer is a network printer connection.
PRINTER_ATTRIBUTE_HIDDEN | Reserved.
PRINTER_ATTRIBUTE_LOCAL | Printer is a local printer.
PRINTER_ATTRIBUTE_RAW_ONLY | Indicates that only RAW data type print jobs can be spooled.

DeviceNotSelectedTimeout
Windows 95: Specifies the maximum time, in milliseconds, allowed to elapse between attempts to select a device.

Windows NT/Windows 2000 or later: This value is not used.

TransmissionRetryTimeout
Windows 95: Specifies the maximum time, in milliseconds, allowed to elapse between transmission retries.

Windows NT/Windows 2000 or later: This value is not used.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPrinters, GetPrinter, SetPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4


PRINTER_INFO_6

The PRINTER_INFO_6 specifies the status value of a printer.

typedef struct _PRINTER_INFO_6 {
  DWORD     dwStatus;
} PRINTER_INFO_6, *PPRINTER_INFO_6;

Members

dwStatus
Specifies the printer status. This member can be any reasonable combination of the following values.
Value | Meaning
PRINTER_STATUS_BUSY | The printer is busy.
PRINTER_STATUS_DOOR_OPEN | The printer door is open.
PRINTER_STATUS_ERROR | The printer is in an error state.
PRINTER_STATUS_INITIALIZING | The printer is initializing.
PRINTER_STATUS_IO_ACTIVE | The printer is in an active input/output state
PRINTER_STATUS_MANUAL_FEED | The printer is in a manual feed state.
PRINTER_STATUS_NO_TONER | The printer is out of toner.
PRINTER_STATUS_NOT_AVAILABLE | The printer is not available for printing.
PRINTER_STATUS_OFFLINE | The printer is offline.
PRINTER_STATUS_OUT_OF_MEMORY | The printer has run out of memory.
PRINTER_STATUS_OUTPUT_BIN_FULL | The printer's output bin is full.
PRINTER_STATUS_PAGE_PUNT The printer cannot print the current page.

Windows 95: Indicates the page is being "punted" (that is, not printed) because it is too complex for the printer to print.

PRINTER_STATUS_PAPER_JAM | Paper is jammed in the printer
PRINTER_STATUS_PAPER_OUT | The printer is out of paper.
PRINTER_STATUS_PAPER_PROBLEM | The printer has a paper problem.
PRINTER_STATUS_PAUSED | The printer is paused.
PRINTER_STATUS_PENDING_DELETION | The printer is pending deletion as a result of a call to the DeletePrinter function.
PRINTER_STATUS_PRINTING | The printer is printing.
PRINTER_STATUS_PROCESSING | The printer is processing a command from the SetPrinter function.
PRINTER_STATUS_TONER_LOW | The printer is low on toner.
PRINTER_STATUS_UNAVAILABLE | The printer is not available for printing.
PRINTER_STATUS_USER_INTERVENTION | The printer has an error that requires the user to do something.
PRINTER_STATUS_WAITING | The printer is waiting.
PRINTER_STATUS_WARMING_UP | The printer is warming up.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, SetPrinter, PRINTER_INFO_1, PRINTER_INFO_2, PRINTER_INFO_3, PRINTER_INFO_4, PRINTER_INFO_5


PRINTER_INFO_7

The PRINTER_INFO_7 structure specifies directory services printer information. Use this structure with the SetPrinter function to publish a printer's data in the directory service (DS), or to update or remove a printer's published data from the DS. Use this structure with the GetPrinter function to determine whether a printer is published in the DS.

typedef struct _PRINTER_INFO_7 {
  LPTSTR   pszObjectGUID;
  DWORD    dwAction;
} PRINTER_INFO_7, *PPRINTER_INFO_7;

Members

pszObjectGUID
Pointer to a null-terminated string containing the GUID of the directory service print queue object associated with a published printer. Use the GetPrinter function to retrieve this GUID.

Before calling SetPrinter, set pszObjectGUID to NULL.

dwAction
Indicates the action for the SetPrinter function to perform. For the GetPrinter function, this member indicates whether the specified printer is published. This member can be one of the following values.
Value Description
DSPRINT_PUBLISH SetPrinter: Publishes the printer's data in the DS.

GetPrinter: Indicates the printer is published.
DSPRINT_UNPUBLISH SetPrinter: Removes the printer's published data from the DS.

GetPrinter: Indicates the printer is not published.
DSPRINT_UPDATE SetPrinter: Updates the printer's published data in the DS.

GetPrinter never returns this value.
DSPRINT_PENDING GetPrinter: Indicates that the system is attempting to complete a publish or unpublish operation started by a SetPrinter call.

This value is not valid for SetPrinter calls.

DSPRINT_REPUBLISH SetPrinter: The DS data for the printer is unpublished and then published again, refreshing all properties in the published printer. Re-publishing also changes the GUID of the published printer.

GetPrinter never returns this value.

Remarks

The PRINTER_INFO_7 structure is used in a SetPrinter call to publish printer information to the directory service. The published data includes all values and data for the specified printer found under the SPLDS_SPOOLER_KEY, SPLDS_DRIVER_KEY, or SPLDS_USER_KEY keys created by SetPrinterDataEx.

For SetPrinter, pszObjectGUID should be set to NULL. For GetPrinter, pszObjectGUID returns the GUID of the directory services print queue object associated with a published printer. You can use this GUID with Active Directory Services Interface (ADSI) methods to retrieve published data for the printer. However, the recommended method for retrieving published data is to call the GetPrinterDataEx function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures


PRINTER_INFO_8

The PRINTER_INFO_8 structure specifies the global default printer settings.

typedef struct _PRINTER_INFO_8 {
  LPDEVMODE pDevMode;
} PRINTER_INFO_8, *PPRINTER_INFO_8;

Members

pDevMode
Pointer to a DEVMODE structure that defines the global default printer data such as the paper orientation and the resolution.

Remarks

The global defaults are set by the administrator of a printer that can be used by anyone. In contrast, the per-user defaults will affect a particular user or anyone else who uses the profile. For per-user defaults, use PRINTER_INFO_9.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GetPrinter, SetPrinter, PRINTER_INFO_9


PRINTER_INFO_9

The PRINTER_INFO_9 structure specifies the per-user default printer settings.

typedef struct _PRINTER_INFO_9 {
  LPDEVMODE pDevMode;
} PRINTER_INFO_9, *PPRINTER_INFO_9;

Members

pDevMode
Pointer to a DEVMODE structure that defines the per-user default printer data such as the paper orientation and the resolution. The DEVMODE is stored in the user's registry.

Remarks

The per-user defaults will affect only a particular user or anyone who uses the profile. In contrast, the global defaults are set by the administrator of a printer that can be used by anyone. For global defaults, use PRINTER_INFO_8.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GetPrinter, SetPrinter, PRINTER_INFO_8


PRINTER_NOTIFY_INFO

The PRINTER_NOTIFY_INFO structure contains printer information returned by the FindNextPrinterChangeNotification function. The function returns this information after a wait operation on a printer change notification object has been satisfied.

typedef struct _PRINTER_NOTIFY_INFO {
  DWORD  Version;
  DWORD  Flags;
  DWORD  Count;
  PRINTER_NOTIFY_INFO_DATA  aData[1];
} PRINTER_NOTIFY_INFO, *PPRINTER_NOTIFY_INFO;

Members

Version
Specifies the version of this structure. Set this member to 2.
Flags
Contains a bit flag to indicate the state of the notification structure. If the PRINTER_NOTIFY_INFO_DISCARDED bit is set, it indicates that some notifications had to be discarded.
Count
Specifies the number of PRINTER_NOTIFY_INFO_DATA elements in the aData array.
aData
An array of PRINTER_NOTIFY_INFO_DATA structures. Each element of the array identifies a single job or printer information field, and provides the current data for that field.

Remarks

If the Flags member has the PRINTER_NOTIFY_INFO_DISCARDED bit set, this indicates that an overflow or error occured, and notifications may have been lost. In this case, you must call FindNextPrinterChangeNotification and specify the PRINTER_NOTIFY_OPTIONS_REFRESH flag to retrieve all current information. Until you request this refresh operation, the system will not send additional notifications for this change notification object.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, FindNextPrinterChangeNotification, PRINTER_NOTIFY_INFO_DATA


PRINTER_NOTIFY_INFO_DATA

The PRINTER_NOTIFY_INFO_DATA structure identifies a job or printer information field and provides the current data for that field.

The FindNextPrinterChangeNotification function returns a PRINTER_NOTIFY_INFO structure, which contains an array of PRINTER_NOTIFY_INFO_DATA structures.

typedef struct _PRINTER_NOTIFY_INFO_DATA {
  WORD   Type;
  WORD   Field;
  DWORD  Reserved;
  DWORD  Id;
  union {
      DWORD  adwData[2];
      struct {
          DWORD  cbBuf;
          LPVOID pBuf;
      } Data;
  } NotifyData;
} PRINTER_NOTIFY_INFO_DATA, *PPRINTER_NOTIFY_INFO_DATA;

Members

Type
Indicates the type of information provided. This member can be one of the following values.
Value | Meaning
PRINTER_NOTIFY_TYPE | Indicates that the Field member specifies a PRINTER_NOTIFY_FIELD_* constant.
JOB_NOTIFY_TYPE | Indicates that the Field member specifies a JOB_NOTIFY_FIELD_* constant.

Field
Indicates the field that changed. For a list of possible values, see the following Remarks section.
Reserved
Reserved.
Id
Indicates the job identifier if the Type member specifies JOB_NOTIFY_TYPE. If the Type member specfies PRINTER_NOTIFY_TYPE, this member is undefined.
NotifyData
A union of data information based on the Type and Field members. For a description of the type of data associated with each field, see the following Remarks section.

The NotifyData union can be one of the following members.
Member | Meaning
adwData | An array of two DWORD values. For information fields that use only a single DWORD, the data is in adwData[0]
Data | The following members are contained in the DATA structure:
Member | Meaning
cbBuf | Indicates the size, in bytes, of the buffer pointed to by pBuf.
pBuf | Pointer to a buffer that contains the field's current data.

Remarks

If the Type member specifies PRINTER_NOTIFY_TYPE, the Field member can be one of the following values.

Field | Type of data
PRINTER_NOTIFY_FIELD_PRINTER_NAME | pBuf is a pointer to a null-terminated string containing the name of the printer.
PRINTER_NOTIFY_FIELD_SHARE_NAME | pBuf is a pointer to a null-terminated string that identifies the sharepoint for the printer.
PRINTER_NOTIFY_FIELD_DRIVER_NAME | pBuf is a pointer to a null-terminated string containing the name of the printer's driver.
PRINTER_NOTIFY_FIELD_COMMENT | pBuf is a pointer to a null-terminated string containing the new comment string, which is typically a brief description of the printer.
PRINTER_NOTIFY_FIELD_LOCATION | pBuf is a pointer to a null-terminated string containing the new physical location of the printer (for example, "Bldg. 38, Room 1164").
PRINTER_NOTIFY_FIELD_DEVMODE | pBuf is a pointer to a DEVMODE structure that defines default printer data such as the paper orientation and the resolution.
PRINTER_NOTIFY_FIELD_SEPFILE | pBuf is a pointer to a null-terminated string that specifies the name of the file used to create the separator page. This page is used to separate print jobs sent to the printer.
PRINTER_NOTIFY_FIELD_PRINT_PROCESSOR | pBuf is a pointer to a null-terminated string that specifies the name of the print processor used by the printer.
PRINTER_NOTIFY_FIELD_PARAMETERS | pBuf is a pointer to a null-terminated string that specifies the default print-processor parameters.
PRINTER_NOTIFY_FIELD_DATATYPE | pBuf is a pointer to a null-terminated string that specifies the data type used to record the print job.
PRINTER_NOTIFY_FIELD_SECURITY_DESCRIPTOR | pBuf is a pointer to a SECURITY_DESCRIPTOR structure for the printer. The pointer may be NULL if there is no security descriptor.
PRINTER_NOTIFY_FIELD_ATTRIBUTES | adwData[0] specifies the printer attributes, which can be one of the following values: PRINTER_ATTRIBUTE_QUEUED PRINTER_ATTRIBUTE_DIRECT PRINTER_ATTRIBUTE_DEFAULT (Windows 95 only) PRINTER_ATTRIBUTE_SHARED
PRINTER_NOTIFY_FIELD_PRIORITY | adwData[0] specifies a priority value that the spooler uses to route print jobs.
PRINTER_NOTIFY_FIELD_DEFAULT_PRIORITY | adwData[0] specifies the default priority value assigned to each print job.
PRINTER_NOTIFY_FIELD_START_TIME | adwData[0] specifies the earliest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)
PRINTER_NOTIFY_FIELD_UNTIL_TIME | adwData[0] specifies the latest time at which the printer will print a job. (This value is specified in minutes elapsed since 12:00 A.M.)
PRINTER_NOTIFY_FIELD_STATUS | adwData[0] specifies the printer status. For a list of possible values, see the PRINTER_INFO_2 structure.
PRINTER_NOTIFY_FIELD_CJOBS | adwData[0] specifies the number of print jobs that have been queued for the printer.
PRINTER_NOTIFY_FIELD_AVERAGE_PPM | adwData[0] specifies the average number of pages per minute that have been printed on the printer.
PRINTER_NOTIFY_FIELD_BYTES_PRINTED | Not supported.
PRINTER_NOTIFY_FIELD_PAGES_PRINTED | Not supported.
PRINTER_NOTIFY_FIELD_PORT_NAME | Not supported.
PRINTER_NOTIFY_FIELD_SERVER_NAME | Not supported.
PRINTER_NOTIFY_FIELD_STATUS_STRING | Not supported.
PRINTER_NOTIFY_FIELD_TOTAL_BYTES | Not supported.
PRINTER_NOTIFY_FIELD_TOTAL_PAGES | Not supported.
PRINTER_NOTIFY_FIELD_OBJECT_GUID | This is set if the object GUID changes.

If the Type member specifies JOB_NOTIFY_TYPE, the Field member can be one of the following values.

Field | Type of data
JOB_NOTIFY_FIELD_PRINTER_NAME | pBuf is a pointer to a null-terminated string containing the name of the printer for which the job is spooled.
JOB_NOTIFY_FIELD_MACHINE_NAME | pBuf is a pointer to a null-terminated string that specifies the name of the machine that created the print job.
JOB_NOTIFY_FIELD_PORT_NAME | pBuf is a pointer to a null-terminated string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of the ports are separated by commas (for example, "LPT1:,LPT2:,LPT3:").
JOB_NOTIFY_FIELD_USER_NAME | pBuf is a pointer to a null-terminated string that specifies the name of the user who sent the print job.
JOB_NOTIFY_FIELD_NOTIFY_NAME | pBuf is a pointer to a null-terminated string that specifies the name of the user who should be notified when the job has been printed or when an error occurs while printing the job.
JOB_NOTIFY_FIELD_DATATYPE | pBuf is a pointer to a null-terminated string that specifies the type of data used to record the print job.
JOB_NOTIFY_FIELD_PRINT_PROCESSOR | pBuf is a pointer to a null-terminated string that specifies the name of the print processor to be used to print the job.
JOB_NOTIFY_FIELD_PARAMETERS | pBuf is a pointer to a null-terminated string that specifies print-processor parameters.
JOB_NOTIFY_FIELD_DRIVER_NAME | pBuf is a pointer to a null-terminated string that specifies the name of the printer driver that should be used to process the print job.
JOB_NOTIFY_FIELD_DEVMODE | pBuf is a pointer to a DEVMODE structure that contains device-initialization and environment data for the printer driver.
JOB_NOTIFY_FIELD_STATUS | adwData[0] specifies the job status. For a list of possible values, see the JOB_INFO_2 structure.
JOB_NOTIFY_FIELD_STATUS_STRING | pBuf is a pointer to a null-terminated string that specifies the status of the print job.
JOB_NOTIFY_FIELD_DOCUMENT | pBuf is a pointer to a null-terminated string that specifies the name of the print job (for example, "MS-WORD: Review.doc").
JOB_NOTIFY_FIELD_PRIORITY | adwData[0] specifies the job priority.
JOB_NOTIFY_FIELD_POSITION | adwData[0] specifies the job's position in the print queue.
JOB_NOTIFY_FIELD_SUBMITTED | pBuf is a pointer to a SYSTEMTIME structure that specifies the time when the job was submitted.
JOB_NOTIFY_FIELD_START_TIME | adwData[0] specifies the earliest time that the job can be printed. (This value is specified in minutes elapsed since 12:00 A.M.)
JOB_NOTIFY_FIELD_UNTIL_TIME | adwData[0] specifies the the latest time that the job can be printed. (This value is specified in minutes elapsed since 12:00 A.M.)
JOB_NOTIFY_FIELD_TIME | adwData[0] specifies the total time, in seconds, that has elapsed since the job began printing.
JOB_NOTIFY_FIELD_TOTAL_PAGES | adwData[0] specifies the size, in pages, of the job.
JOB_NOTIFY_FIELD_PAGES_PRINTED | adwData[0] specifies the number of pages that have printed.
JOB_NOTIFY_FIELD_TOTAL_BYTES | adwData[0] specifies the size, in bytes, of the job.
JOB_NOTIFY_FIELD_BYTES_PRINTED | adwData[0] specifies the number of bytes that have been printed on this job. For this field, the change notification object is signaled when bytes are sent to the printer.
JOB_NOTIFY_FIELD_SECURITY_DESCRIPTOR | Not supported.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, DEVMODE, FindNextPrinterChangeNotification, JOB_INFO_2, PRINTER_INFO_2, PRINTER_NOTIFY_INFO, SECURITY_DESCRIPTOR, SYSTEMTIME


PRINTER_NOTIFY_OPTIONS

The PRINTER_NOTIFY_OPTIONS structure specifies options for a change notification object that monitors a printer or print server.

typedef struct _PRINTER_NOTIFY_OPTIONS {
  DWORD  Version;
  DWORD  Flags;
  DWORD  Count;
  PPRINTER_NOTIFY_OPTIONS_TYPE  pTypes;
} PRINTER_NOTIFY_OPTIONS, *PPRINTER_NOTIFY_OPTIONS;

Members

Version
Specifies the version of this structure. Set this member to 2.
Flags
Contains a bit flag. If you set the PRINTER_NOTIFY_OPTIONS_REFRESH flag in a call to the FindNextPrinterChangeNotification function, the function provides current data for all monitored printer information fields. The FindFirstPrinterChangeNotification function ignores the Flags member.
Count
Specifies the number of elements in the pTypes array.
pTypes
Pointer to an array of PRINTER_NOTIFY_OPTIONS_TYPE structures. Use one element of this array to specify the printer information fields to monitor, and one element to specify the job information fields to monitor. You can monitor either printer information, job information, or both.

Remarks

Use this structure with the FindFirstPrinterChangeNotification function to specify the set of printer or job information fields to monitor for change.

Use this structure with the FindNextPrinterChangeNotification function to request the current data for all monitored printer and job information fields. In this case, the Flags member specifies the PRINTER_NOTIFY_OPTIONS_REFRESH flag, and the function ignores the other structure members.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, FindFirstPrinterChangeNotification, FindNextPrinterChangeNotification, PRINTER_NOTIFY_OPTIONS_TYPE


PRINTER_NOTIFY_OPTIONS_TYPE

The PRINTER_NOTIFY_OPTIONS_TYPE structure specifies the set of printer or job information fields to be monitored by a printer change notification object.

A call to the FindFirstPrinterChangeNotification function specifies a PRINTER_NOTIFY_OPTIONS structure, which contains an array of PRINTER_NOTIFY_OPTIONS_TYPE structures.

typedef struct _PRINTER_NOTIFY_OPTIONS_TYPE {
  WORD   Type;
  WORD   Reserved0;
  DWORD  Reserved1;
  DWORD  Reserved2;
  DWORD  Count;
  PWORD  pFields;
} PRINTER_NOTIFY_OPTIONS_TYPE, *PPRINTER_NOTIFY_OPTIONS_TYPE;

Members

Type
Specifies the type to watch. This member can be one of the following values.
Value | Meaning
PRINTER_NOTIFY_TYPE | Indicates that the fields specified in the pFields array are PRINTER_NOTIFY_FIELD_* constants.
JOB_NOTIFY_TYPE | Indicates that the fields specified in the pFields array are JOB_NOTIFY_FIELD_* constants.

Reserved0
Reserved.
Reserved1
Reserved.
Reserved2
Reserved.
Count
Specifies the number of elements in the pFields array.
pFields
Pointer to an array of 16-bit values. Each element of the array specifies a job or printer information field of interest. For a list of supported printer and job information fields, see the PRINTER_NOTIFY_INFO_DATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, FindFirstPrinterChangeNotification, PRINTER_NOTIFY_INFO_DATA, PRINTER_NOTIFY_OPTIONS


PRINTPROCESSOR_CAPS_1

The PRINTPROCESSOR_CAPS_1 structure is the format for the printer capability information that is returned by the GetPrinterData function in the buffer specified by the pData variable.

typedef struct _PRINTPROCESSOR_CAPS_1 {
  DWORD    dwLevel;
  DWORD    dwNupOptions;
  DWORD    dwPageOrderFlags;
  DWORD    dwNumberOfCopies;
} PRINTPROCESSOR_CAPS_1, *PPRINTPROCESSOR_CAPS_1;

Members

dwLevel
Value that indicates the structure's version number. This value must be 1.
dwNupOptions
Bit mask representing the various numbers of document pages the printer can print on a physical page. The least significant bit represents 1 document page per page, the next bit represents 2 document pages per page, and so on. For example, 0x0000810B indicates the printer supports 1, 2, 4, 9, and 16 document pages per physical page.
dwPageOrderFlags
Flag value that indicates the order in which pages will be printed. It can be either NORMAL_PRINT or REVERSE_PRINT.
dwNumberOfCopies
Maximum number of copies the printer can handle.

Remarks

Values for all structure members are supplied by the GetPrintProcessorCapabilities function, which is documented in the Windows DDK.

The spooler calls a print processor's GetPrintProcessorCapabilities function when an application calls GetPrinterData, specifying a value name with a format of PrintProcCaps_datatype, where datatype is the name of an input data type.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GetPrinterData


PRINTPROCESSOR_INFO_1

The PRINTPROCESSOR_INFO_1 structure specifies the name of an installed print processor.

typedef struct _PRINTPROCESSOR_INFO_1 {
  LPTSTR pName;
} PRINTPROCESSOR_INFO_1, *PPRINTPROCESSOR_INFO_1;

Members

pName
Pointer to a null-terminated string that specifies the name of an installed print processor.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, EnumPrintProcessors


PROVIDOR_INFO_1

The PROVIDOR_INFO_1 structure identifies a print provider.

typedef struct _PROVIDOR_INFO_1 {
  LPTSTR pName;
  LPTSTR pEnvironment;
  LPTSTR pDLLName;
} PROVIDOR_INFO_1, *PPROVIDOR_INFO_1;

Members

pName
Pointer to a null-terminated string that is the name of the print provider.
pEnvironment
Pointer to a null-terminated environment string specifying the environment the provider dynamic-link library (DLL) is designed to run in.
pDLLName
Pointer to a null-terminated string that is the name of the provider .dll.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrintProvidor


PROVIDOR_INFO_2

The PROVIDOR_INFO_2 structure appends a print provider to the print provider order list.

typedef struct _PROVIDOR_INFO_2{
  LPTSTR pOrder;
} PROVIDOR_INFO_2, *PPROVIDOR_INFO_2;

Members

pOrder
Pointer to a null-terminated string that specifies the name of the print provider.

Remarks

This structure is used when calling AddPrintProvidor, level 2, to add the specified print provider to the end of the print provider order list. The provider is immediately used for routing if the call succeeds.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winspool.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, AddPrintProvidor


PSFEATURE_CUSTPAPER

The PSFEATURE_CUSTPAPER structure contains information about a custom paper size for a PostScript driver. This structure is used with the GET_PS_FEATURESETTING printer escape function.

typedef struct _PSFEATURE_CUSTPAPER {
  LONG lOrientation;
  LONG lWidth;
  LONG lHeight;
  LONG lWidthOffset;
  LONG lHeightOffset;
} PSFEATURE_CUSTPAPER, *PPSFEATURE_CUSTPAPER;

Members

lOrientation
Indicates the custom paper orientation. This member can be 0 to 3 if custom page size is selected. Otherwise, it is –1 and all other structure members are zero
lWidth
Custom page width, in points.
lHeight
Custom page height, in points.
lWidthOffset
Custom page width offset, in points.
lHeightOffset
Custom page height offset, in points.

Remarks

For the semantics of the lOrientation, lWidth, lHeight, lWidthOffset, and lHeightOffset members, please refer to "Custom Page Size Parameters" in "PostScript Printer Description File Format Specification" v.4.3.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GET_PS_FEATURESETTING


PSFEATURE_OUTPUT

The PSFEATURE_OUTPUT structure contains information about PostScript driver output options. This structure is used with the GET_PS_FEATURESETTING printer escape function.

typedef struct _PSFEATURE_OUTPUT {
  BOOL bPageIndependent;
  BOOL bSetPageDevice;
} PSFEATURE_OUTPUT, *PPSFEATURE_OUTPUT;

Members

bPageIndependent
Specifies TRUE if PostScript output is page-independent or FALSE if PostScript output is page-dependent.
bSetPageDevice
Specifies TRUE if printer feature code (setpagedevice's) is included or FALSE if all printer feature code is suppressed.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, GET_PS_FEATURESETTING


PSINJECTDATA

The PSINJECTDATA structure is a header for the input buffer used with the POSTSCRIPT_INJECTION printer escape function.

typedef struct _PSINJECTDATA {
  DWORD   DataBytes;
  WORD    InjectionPoint;
  WORD    PageNumber;
} PSINJECTDATA, *PPSINJECTDATA;

Members

DataBytes
Specifies the number of bytes of raw data to be injected. The raw data begins immediately following this structure. This size does not include the size of the PSINJECTDATA structure.
InjectionPoint
Specifies where to inject the raw data in the PostScript output. This member can be one of the following values.
Value | Meaning
PSINJECT_BEGINSTREAM | Before the first byte of job stream.
PSINJECT_PSADOBE | Before %!PS-Adobe.
PSINJECT_PAGESATEND | Replaces driver's %%Pages (atend).
PSINJECT_PAGES | Replaces driver's %%Pages nnn.
PSINJECT_DOCNEEDEDRES | After %%DocumentNeededResources.
PSINJECT_DOCSUPPLIEDRES | After %%DocumentSuppliedResources.
PSINJECT_PAGEORDER | Replaces driver's %%PageOrder.
PSINJECT_ORIENTATION | Replaces driver's %%Orientation.
PSINJECT_BOUNDINGBOX | Replaces driver's %%BoundingBox.
PSINJECT_DOCUMENTPROCESSCOLORS | Replaces driver's %DocumentProcessColors <color>.
PSINJECT_COMMENTS | Before %%EndComments.
PSINJECT_BEGINDEFAULTS | After %%BeginDefaults.
PSINJECT_ENDDEFAULTS | Before %%EndDefaults.
PSINJECT_BEGINPROLOG | After %%BeginProlog.
PSINJECT_ENDPROLOG | Before %%EndProlog.
PSINJECT_BEGINSETUP | After %%BeginSetup.
PSINJECT_ENDSETUP | Before %%EndSetup.
PSINJECT_TRAILER | After %%Trailer
PSINJECT_EOF | After %%EOF
PSINJECT_ENDSTREAM | After the last byte of job stream
PSINJECT_DOCUMENTPROCESSCOLORSATEND | Replaces driver's %%DocumentProcessColors (atend)
Page level injection points
PSINJECT_PAGENUMBER | Replaces driver's %%Page
PSINJECT_BEGINPAGESETUP | After %%BeginPageSetup
PSINJECT_ENDPAGESETUP | Before %%EndPageSetup
PSINJECT_PAGETRAILER | After %%PageTrailer
PSINJECT_PLATECOLOR | Replace driver's %%PlateColor: <color>
PSINJECT_SHOWPAGE | Before showpage operator
PSINJECT_PAGEBBOX | Replaces driver's %%PageBoundingBox
PSINJECT_ENDPAGECOMMENTS | Before %%EndPageComments
PSINJECT_VMSAVE | Before save operator
PSINJECT_VMRESTORE | After restore operator

PageNumber
Specifies the page number (starting from 1) to which the injection data is applied. Specify zero to apply the injection data to all pages. This member is meaningful only for page level injection points starting from PSINJECT_PAGENUMBER. For other injection points, set PageNumber to zero.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Structures, POSTSCRIPT_INJECTION


Printing and Print Spooler Messages

The following message is used with the print spooler.

WM_SPOOLERSTATUS


WM_SPOOLERSTATUS

The WM_SPOOLERSTATUS message is sent from Print Manager whenever a job is added to or removed from the Print Manager queue.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SPOOLERSTATUS
  WPARAM wParam,   // job status
  LPARAM lParam    // number of jobs remaining
);

Parameters

wParam
Specifies the PR_JOBSTATUS flag.
lParam
The low-order word specifies the number of jobs remaining in the Print Manager queue.

Return Values

An application should return zero if it processes this message.

Remarks

This message is for informational purposes only. This message is advisory and does not have guaranteed delivery semantics. Applications should not assume that they will receive a WM_SPOOLERSTATUS message for every change in spooler status.

Windows NT/2000 or later: Requires Windows NT 3.5 through 4.0; not supported on Windows 2000.

Windows 2000 or later: The WM_SPOOLERSTATUS message is not sent. To be notified of changes to the print queue status, use FindFirstPrinterChangeNotification and FindNextPrinterChangeNotification. The following code outlines how this might be done.

HANDLE chgObject;
DWORD *pdwChange;
BOOL fcnreturn;

chgObject = FindFirstPrinterChangeNotification( hPrinter, PRINTER_CHANGE_JOB, 0, NULL);
WaitForSingleObject(chgObject, INFINTE);
fcnreturn = FindNextPrinterChangeNotification(chgObject, pdwChange, NULL, NULL);
if (fcnreturn) {
     // check value of *pdwChange and deal with the indicated change

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Messages, LOWORD, FindFirstPrinterChangeNotification and FindNextPrinterChangeNotification


Printer Escape Functions

The following printer escape functions are used with the Escape or ExtEscape functions.

Printer escape function | Description
CHECKJPEGFORMAT | Windows 2000 or later: Checks whether the printer supports a JPEG image.
CHECKPNGFORMAT | Windows 2000 or later: Checks whether the printer supports a PNG image.
DRAWPATTERNRECT | Draws a white, gray-scale, or black rectangle.
GET_PS_FEATURESETTING | Windows 2000 or later: Gets information on a specified feature setting for a PostScript driver.
PASSTHROUGH | Sends data directly to a printer driver in compatibility mode or GDI-centric mode.
POSTSCRIPT_DATA | Sends data directly to a printer driver in compatibility mode only.
POSTSCRIPT_IDENTIFY | Windows 2000 or later: Sets a PostScript driver to GDI-centric or PostScript-centric mode.
POSTSCRIPT_INJECTION | Windows 2000 or later: Inserts a block of raw data in a PostScript job stream.
POSTSCRIPT_PASSTHROUGH | Windows 2000 or later: Sends data directly to a PostScript printer driver in compatibility mode or PostScript-centric mode.
SPCLPASSTHROUGH2 | Windows 2000 or later: Allows applications to include private procedures and other resources at the document level-save context.


CHECKJPEGFORMAT

The CHECKJPEGFORMAT printer escape function determines whether a printer can handle a JPEG image.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                   // handle to DC (HDC)
  CHECKJPEGFORMAT,       // nEscape parameter of ExtEscape
  cbInput,               // size of JPEG image
  lpszInData,            // pointer to JPEG image
  sizeof(DWORD),         // cbOutput parameter of ExtEscape
  lpszOutData            // pointer to the output buffer
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the lpszInData buffer containing the JPEG image.
lpszInData
Pointer to a buffer containing the JPEG image.
lpszOutData
Pointer to a variable that receives the results. If the printer can handle the image, the variable returns 1. Otherwise, it returns zero.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

Before using the CHECKJPEGFORMAT printer escape function, call the QUERYESCSUPPORT printer escape function to determine whether the driver supports CHECKJPEGFORMAT. For sample code that illustrates the use of CHECKJPEGFORMAT, see Testing a Printer for JPEG or PNG Support.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, CHECKPNGFORMAT


CHECKPNGFORMAT

The CHECKPNGFORMAT printer escape function determines whether a printer can handle a PNG image.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,               // handle to DC (HDC)
  CHECKPNGFORMAT,    // nEscape parameter of ExtEscape
  cbInput,           // size of PNG image
  lpszInData,        // pointer to PNG image
  sizeof(DWORD),     // the cbOutput parameter of ExtEscape
  lpszOutData        // pointer to the output buffer
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the lpszInData buffer containing the PNG image.
lpszInData
Pointer to a buffer containing the PNG image.
lpszOutData
Pointer to a variable that receives the results. If the printer can handle the image, the variable returns 1. Otherwise, it returns zero.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

Before using the CHECKPNGFORMAT printer escape function, call the QUERYESCSUPPORT printer escape function to determine whether the driver supports CHECKPNGFORMAT. For sample code, see Testing a Printer for JPEG or PNG Support.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, CHECKJPEGFORMAT


DRAWPATTERNRECT

The DRAWPATTERNRECT printer escape creates a white, gray scale, or solid black rectangle by using the pattern and rule capabilities of Page Control Language (PCL) on Hewlett-Packard® LaserJet or LaserJet-compatible printers. A gray scale is a gray pattern that contains a specific mixture of black and white pixels.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  (HDC) hdc,           // handle to device context
  DRAWPATTERNRECT,     // nEscape parameter of ExtEscape
  sizeof(DRAWPATRECT), // cbInput parameter of ExtEscape
  lpszInData,          // pointer to mode variable
  0,                   // cbOutput parameter of ExtEscape
  NULL                 // lpszOutData parameter of ExtEscape
);

Parameters

hdc
Identifies the printer device context.
nEscape
Specifies the escape function to be performed. Use DRAWPATTERNRECT for this operation.
cbInput
Specifies the number of bytes of data pointed to by the lpszInData parameter. Set this parameter to sizeof(DRAWPATRECT).
lpszInData
Pointer to a DRAWPATRECT structure that describes the rectangle.
cbOutput
Specifies the number of bytes of data pointed to by the lpszOutData parameter. Set this parameter to zero.
lpszOutData
Pointer to a buffer to receive output. Set this parameter to NULL.

Return Values

If the function succeeds, the return value is 1. Otherwise it is zero.

Remarks

An application should use the QUERYESCSUPPORT escape to determine whether a device is capable of drawing patterns and rules before using the DRAWPATTERNRECT escape.

Applications that use the DRAWPATTERNRECT escape must observe two limitations. First, rules drawn with DRAWPATTERNRECT are not subject to clipping regions in the device context. Second, applications should not try to erase patterns and rules created with DRAWPATTERNRECT by placing opaque objects over them. If the printer supports white rules, these can be used to erase patterns created by DRAWPATTERNRECT. If the printer does not support white rules, there is no method for erasing these patterns.

If an application cannot use the DRAWPATTERNRECT escape, it should generally use the PatBlt function instead. (If PatBlt is used to print a black rectangle, the application should use the BLACKNESS raster operator.) If the device is a plotter, the application should use the Rectangle function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, PatBlt , DRAWPATRECT


GET_PS_FEATURESETTING

The GET_PS_FEATURESETTING printer escape function retrieves information about a specified feature setting for a PostScript driver.

This escape function is supported only if the PostScript driver is in PostScript-centric mode or GDI-centric mode. To set the PostScript driver's mode, call the POSTSCRIPT_IDENTIFY escape function.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                    // handle to DC (HDC)
  GET_PS_FEATURESETTING,  // nEscape parameter of ExtEscape
  sizeof(INT),            // cbInput parameter of ExtEscape
  lpszInData,             // pointer to input data
  cbOutput,               // size of output buffer
  lpszOutData             // pointer to output buffer
);

Parameters

hdc
Handle to the printer device context.
lpszInData
Pointer to a variable that specifies the feature of interest. This parameter can be one of the following values.
Value Meaning
FEATURESETTING_CUSTPAPER Retrieves the custom paper parameters.

Set cbOutput to sizeof(PSFEATURE_CUSTPAPER) and lpszOutData to point to a PSFEATURE_CUSTPAPER structure.

FEATURESETTING_MIRROR Retrieves the mirrored output setting.

Set cbOutput to sizeof(BOOL) and lpszOutData to point to a BOOL variable.

When the function returns, the lpszOutData variable is TRUE if "Mirrored Output: Yes" is selected; otherwise, it is FALSE.
FEATURESETTING_NEGATIVE Retrieves the negative output setting.

Set cbOutput to sizeof(BOOL) and lpszOutData to point to a BOOL variable.

When the function returns, the lpszOutData variable is TRUE if "Negative Output: Yes" is selected; otherwise, it is FALSE.
FEATURESETTING_NUP Retrieves the page layout (N-Up) setting.

Set cbOutput to sizeof(BOOL) and lpszOutData to point to a BOOL variable.

If N-Up is not being done, the lpszOutData variable returns FALSE.

If N-Up is being done, the lpszOutData variable returns TRUE. However, the variable does not indicate which N-Up is being done or the semantics of that N-Up.
FEATURESETTING_OUTPUT Retrieves information about PostScript driver output options.

Set cbOutput to sizeof(PSFEATURE_OUTPUT) and lpszOutData to point to a PSFEATURE_OUTPUT structure.

FEATURESETTING_PROTOCOL Retrieves the output protocol setting.

Sets cbOutput to sizeof(INT) and lpszOutData to point to an INT variable.

When the function returns, the lpszOutData variable indicates the output protocol of the driver. It is one of the following:

PSPROTOCOL_ASCII

PSPROTOCOL_BCP

PSPROTOCOL_TBCP

PSPROTOCOL_BINARY
FEATURESETTING_PSLEVEL Retrieves the PostScript language level.

Set cbOutput to sizeof(INT) and lpszOutData to point to an INT variable.

When the function returns, the lpszOutData variable is set to 1, 2, 3, or higher to indicate the PostScript language level.

cbOutput
Specifies the size, in bytes, of the lpszOutData buffer. The required size depends on the value of the lpszInData parameter.
lpszOutData
Pointer to a buffer that receives output from this escape function. The type of output depends on the value of the lpszInData parameter.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

The GET_PS_FEATURESETTING printer escape function is valid if called any time after calling the CreateDC function and before calling the DeleteDC function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, CreateDC, DeleteDC, ExtEscape, PSFEATURE_CUSTPAPER, PSFEATURE_OUTPUT


PASSTHROUGH

The PASSTHROUGH printer escape function sends data directly to a printer driver. To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                 // handle to DC (HDC)
  PASSTHROUGH,         // nEscape parameter of ExtEscape
  cbInput,             // bytes in input buffer
  lpszInData,          // data to send to printer
  0,                   // cbOutput parameter of ExtEscape
  NULL                 // lpszOutData parameter of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the data pointed to by the lpszInData parameter.
lpszInData
Pointer to a buffer containing the data to send to the printer. The buffer's first word (16-bits) contains the number of bytes of input data. The remaining bytes of the buffer contain the data itself.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

The PASSTHROUGH printer escape function is supported by PostScript drivers in GDI-centric mode or compatibility mode. It is not supported by PostScript drivers in PostScript-centric mode. Drivers in PostScript-centric mode can use the POSTSCRIPT_PASSTHROUGH escape function. To set a PostScript driver's mode, call the POSTSCRIPT_IDENTIFY escape function.

For PASSTHROUGH data sent by EPSPRINTING or PostScript-centric applications, the PostScript driver will not make any modifications. For PASSTHROUGH data sent by other applications, if the PostScript driver is using BCP (Binary Communication Protocol) or TBCP (Tagged Binary Communication Protocol) output protocol, it will do the appropriate BCP or TBCP quoting on special characters as described in "Adobe Serial and Parallel Communications Protocols Specification." This means that the application should send either ASCII or pure binary PASSTHROUGH data.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, POSTSCRIPT_DATA, POSTSCRIPT_IDENTIFY, POSTSCRIPT_PASSTHROUGH


POSTSCRIPT_DATA

The POSTSCRIPT_DATA printer escape function sends data directly to a printer driver. To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                 // handle to DC (HDC)
  POSTSCRIPT_DATA,     // nEscape parameter of ExtEscape
  cbInput,             // bytes in input buffer
  lpszInData,          // data to send to printer
  0,                   // cbOutput parameter of ExtEscape
  NULL                 // lpszOutData parameter of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the data pointed to by the lpszInData parameter.
lpszInData
Pointer to a buffer containing the data to send to the printer. The buffer's first word (16-bits) contains the number of bytes of input data. The remaining bytes of the buffer contain the data itself.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

Windows NT/Windows 2000 or later: To get extended error information, call GetLastError.

Remarks

The POSTSCRIPT_DATA function is identical to the PASSTHROUGH escape function except that it is supported by PostScript drivers in compatibility mode only. It is not supported by PostScript drivers in PostScript-centric mode or in GDI-centric mode.

Drivers in PostScript-centric mode can use the POSTSCRIPT_PASSTHROUGH escape function, and drivers in GDI-centric mode can use the PASSTHROUGH escape function. To set a PostScript driver's mode, call the POSTSCRIPT_IDENTIFY escape function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, PASSTHROUGH, POSTSCRIPT_IDENTIFY, POSTSCRIPT_PASSTHROUGH


POSTSCRIPT_IDENTIFY

The POSTSCRIPT_IDENTIFY printer escape function sets a PostScript driver to GDI-centric mode or PostScript-centric mode.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                 // handle to DC (HDC)
  POSTSCRIPT_IDENTIFY, // nEscape parameter of ExtEscape
  sizeof(DWORD),       // cbInput parameter of ExtEscape
  lpszInData,          // pointer to mode (DWORD *)
  0,                   // cbOutput parameter of ExtEscape
  NULL                 // lpszOutData parameter of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
lpszInData
Pointer to a variable that contains one of the following values.
Value | Meaning
PSIDENT_GDICENTRIC | GDI-centric mode. The PostScript driver supports the PASSTHROUGH escape function, but not the POSTSCRIPT_PASSTHROUGH escape function.
PSIDENT_PSCENTRIC | PostScript-centric mode. The PostScript driver supports the POSTSCRIPT_PASSTHROUGH escape function, but not the PASSTHROUGH escape function.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

To put the driver in GDI-centric or PostScript-centric modes, call the QUERYESCSUPPORT printer escape function to determine whether the driver supports the POSTSCRIPT_IDENTIFY printer escape function. If the QUERYESCSUPPORT call indicates success, you can assume the driver is PSCRIPT 5.0. You must then call POSTSCRIPT_IDENTIFY with the PSIDENT_GDICENTRIC or PSIDENT_PSCENTRIC parameter. You must make the QUERYESCSUPPORT and POSTSCRIPT_IDENTIFY calls before calling any other printer escape function.

Note, after the PostScript driver is set to GDI-centric mode or PostScript-centric mode, you will not be allowed to call the POSTSCRIPT_IDENTIFY printer escape function anymore.

If you do not use the POSTSCRIPT_IDENTIFY escape function, the PostScript driver is in compatibility mode and provides identical support for the PASSTHROUGH, POSTSCRIPT_PASSTHROUGH, and POSTSCRIPT_DATA escape functions.

For PostScript drivers that support the POSTSCRIPT_PASSTHROUGH escape function, the PASSTHROUGH and POSTSCRIPT_PASSTHROUGH escape functions are identical.

In PostScript-centric mode, the application is responsible for all PostScript output that marks the paper using the POSTSCRIPT_PASSTHROUGH escape function. No GDI functions are allowed. The driver is responsible for the overall document structure and printer control settings. The application can use the POSTSCRIPT_INJECTION escape function to inject a block of raw data (including DSC comments) into the job stream at specific places.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, PASSTHROUGH, POSTSCRIPT_PASSTHROUGH


POSTSCRIPT_INJECTION

The POSTSCRIPT_INJECTION printer escape function inserts a block of raw data at specified points in a PostScript job stream.

PostScript drivers in GDI-centric mode and PostScript-centric mode support this escape function. Drivers in compatibility mode do not support it. To set the PostScript driver's mode, call the POSTSCRIPT_IDENTIFY escape function.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                  // handle to DC (HDC)
  POSTSCRIPT_INJECTION, // nEscape param of ExtEscape
  cbInput,              // size of input buffer
  lpszInData,           // pointer to input (PSINJECTDATA *)
  0,                    // cbOutput param of ExtEscape
  NULL                  // lpszOutData param of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the buffer pointed to by the lpszInData parameter. Set this parameter to sizeof(PSINJECTDATA) plus the size of the raw data to inject.
lpszInData
Pointer to a PSINJECTDATA structure followed by the raw data to inject.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

The injection data for a specified injection point is cumulative. In other words, POSTSCRIPT_INJECTION adds the new injection data to any injection data previously specified for the same injection point.

If the job is in EMF data type, you must provide all injection data before StartDoc by using the POSTSCRIPT_INJECTION printer escape function.

If the job is in RAW data type, you must provide the following injection data before the driver needs it:

  • Data for header sections (before first %%Page:) before calling the first StartPagefunction.
  • Data for page setup sections (when injecting data for one particular page) before calling the StartPage function for that particular page.
  • Data for page setup sections (when injecting data for all pages starting from a certain page) before calling StartPage for the starting page.
  • Data for page trailer sections before calling the EndPage function.
  • Data for document trailer sections before calling the EndDoc function.

The driver internally caches the injection data and emits it at appropriate points in the output. The cached information is flushed when it is no longer needed. At the latest, it is flushed after the EndDoc call.

In GDI-centric mode, the application can only inject valid DSC block data by using the POSTSCRIPT_INJECTION printer escape function. A valid DSC block must satisfy all of the following conditions:

  • It's composed by an integral sequence of "lines".
  • A "line" must begin with "%%".
  • A "line" must end with <CR>, <LF>, or <CR><LF> except for the last line. If the last line does not end with <CR>, <LF>, or <CR><LF>, the driver appends <CR><LF> after the last byte of the injection data.
  • A "line" must be 255 bytes or less including the "%%" but not counting the <CR>/<LF> line termination.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, PSINJECTDATA


POSTSCRIPT_PASSTHROUGH

The POSTSCRIPT_PASSTHROUGH printer escape function sends data directly to a PostScript printer driver.

PostScript drivers in PostScript-centric mode and compatibility mode support this escape function. Drivers in GDI-centric mode do not support it. To set the PostScript driver's mode, call the POSTSCRIPT_IDENTIFY escape function.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,                     // handle to DC (HDC)
  POSTSCRIPT_PASSTHROUGH,  // nEscape param of ExtEscape
  cbInput,                 // bytes in input buffer
  lpszInData,              // pointer to data
  0,                       // cbOutput param of ExtEscape
  NULL                     // lpszOutData param of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the data pointed to by the lpszInData parameter.
lpszInData
Pointer to a buffer containing the data to send to the printer. The buffer's first word (16-bits) contains the number of bytes of input data. The remaining bytes of the buffer contain the data itself.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape, PASSTHROUGH, POSTSCRIPT_DATA, POSTSCRIPT_IDENTIFY


SPCLPASSTHROUGH2

The SPCLPASSTHROUGH2 printer escape function allows applications that print to PostScript devices using EPSPRINTING to include private PostScript procedures and other resources at the document level–save context.

This escape is supported only for backward compatibility with Adobe Acrobat. Other applications should not use this obsolete escape.

To perform this operation, call the ExtEscape function with the following parameters.

int ExtEscape(
  hdc,               // handle to device context (HDC)
  SPCLPASSTHROUGH2,  // nEscape parameter of ExtEscape
  cbInput,           // bytes in input buffer
  lpszInData,        // pointer to input data
  0,                 // cbOutput parameter of ExtEscape
  NULL               // lpszOutData parameter of ExtEscape
);

Parameters

hdc
Handle to the printer device context.
cbInput
Specifies the size, in bytes, of the data pointed to by the lpszInData parameter.
lpszInData
Pointer to a buffer containing the input data.

The input data buffer has the following format: the first four bytes contains the estimate of the number of bytes of printer virtual memory used by the PostScript data; the next 2 bytes is the number of bytes of raw PostScript data; then comes the actual PostScript data.

Return Values

If the function succeeds, the return value is greater than zero. If the function fails or is not supported, the return value is less than or equal to zero.

To get extended error information, call GetLastError.

Remarks

The application must call this escape before calling STARTDOC so that the driver will cache the data for insertion at the correct point in the PostScript stream. If this escape is supported, the driver will also allow escape DOWNLOADFACE calls prior to STARTDOC. The driver internally caches the data to be inserted and the data required by any escape DOWNLOADFACE calls prior to STARTDOC and emits them all immediately before %%EndProlog. The sequence of SPCLPASSTHROUGH2 and DOWNLOADFACE calls will be preserved in the order their data is passed in, that is, a later call results in data output after an earlier call's data. The driver will consider fonts downloaded by pre-STARTDOC escape DOWNLOADFACE calls as unavailable for removal during the scope of the job.

This escape is not recorded in EMF files by the operating system, therefore applications must ensure that EMF recording is turned off for those jobs using the escape.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Printing and Print Spooler Overview, Printer Escape Functions, ExtEscape


Bidi Communication Interfaces

Platform SDK: Windows GDI

Printing and Print Spooler Interfaces

The following interfaces are used in bidi communication.

Interface | Description
IBidiRequest | Used to compose a bidi request.
IBidiRequestContainer | Used to compose and retrieve a list of bidi requests.
IBidiSpl | Used to send a bidi request or a list of bidi requests.


IBidiRequest

[This is preliminary documentation and subject to change.]

The IBidiRequest interface allows an application or other objects to compose a bidi request.

IBidiRequest Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IBidiRequest Methods

Method | Description
SetSchema | Sets the bidi schema string.
SetInputData | Sets the data to send to the device.
GetResult | Gets the result code.
GetOutputData | Gets the output data coming back from the device.
GetEnumCount | Gets the number of output items.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiRequest::SetSchema

[This is preliminary documentation and subject to change.]

The IBidiRequest::SetSchema method sets the bidi schema string.

HRESULT IBidiRequest::SetSchema(
  const LPCWSTR pszSchema
)

Parameters

pszSchema
[in] Pointer to a schema string.

Return Values

SetSchema returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiRequest::SetInputData

[This is preliminary documentation and subject to change.]

The IBidiRequest::SetInputData method sets the data to send to the printer.

HRESULT IBidiRequest::SetInputData(
  const DWORD dwType,
  const BYTE *pData,
  const UINT uSize
)

Parameters

dwType
[in] A DWORD that indicates the type of data to be sent. It is one of the BIDI_TYPE enum values, as described in the Windows DDK documentation.
pData
[in] Pointer to the byte array that contains the data. For example, if dwType is BIDI_BOOL, pData points to a buffer that contains a Boolean value and if dwType is BIDI_BLOB, pData points to a buffer that contains the binary data.
uSize
[in] Size, in bytes, of the byte array specified by pData.

Return Values

SendInputData returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
E_INVALIDARG | The type of the data was not consistent with its size.
E_OUTOFMEMORY | Memory allocation failed.
None of the above | The HRESULT contains an error code corresponding to the last error.

Remarks

If an application calls SetInputData more than once, only the value of the last call will be set.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiRequest::GetResult

[This is preliminary documentation and subject to change.]

The IBidiRequest::GetResult method tells whether the bidi request was successful.

HRESULT IBidiRequest::GetResult(
  HRESULT *phr
);

Parameters

phr
[out] Pointer to the HRESULT value that tells what happened to the bidi request.

Return Values

GetResult returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
E_POINTER | At least one of the pointer variable parameters did not reference a valid memory location.
None of the above | The HRESULT contains an error code corresponding to the last error.

Note that the return value indicates whether the GetResult method was successful. It does not indicate what happened to the bidi request.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiRequest::GetOutputData

[This is preliminary documentation and subject to change.]

The IBidiRequest::GetOutputData method gets the specified output data coming back from the printer.

HRESULT IBidiRequest::GetOutputData(
  const DWORD dwIndex,
  LPWSTR   *ppszSchema,
  DWORD    *pdwType,
  BYTE     **ppData,
  ULONG    *uSize
)

Parameters

dwIndex
[in] Zero-based index of the output data that is requested. For more information, see Remarks.
ppszSchema
[out] Pointer to a NULL-terminated string that receives the schema string. The caller must call CoTaskMemFree() to free this pointer.
pdwType
[out] Pointer to a DWORD that receives the type of the output data. This can be one of the BIDI_TYPE enum values, as described in the Windows DDK documentation.
ppData
[out] Pointer to the variable that receives a pointer to the byte array containing the output data. The buffer is allocated by the COM interface to store the output data. The caller is responsible for calling CoTaskMemFree() to free the buffer.

uSize

[out] Pointer to a ULONG that receives the size of the byte array specified by **ppData.

Return Values

GetOutputData returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
E_POINTER | At least one of the pointer variable parameters did not reference a valid memory location.
None of the above | The HRESULT contains an error code corresponding to the last error.

Remarks

A single bidi request can have multiple results. The application calls IBidiRequest::GetEnumCount to get the number of results from the bidi request.

If an application calls GetOutputData with the same index twice, the interface allocates two different buffers and thus the application must free both buffers.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, IBidiRequest::GetEnumCount


IBidiRequest::GetEnumCount

[This is preliminary documentation and subject to change.]

The IBidiRequest::GetEnumCount method gets the number of output results from the bidi request.

HRESULT IBidiRequest::GetEnumCount(
  DWORD *pdwTotal
)

Parameters

pdwTotal
[out] Pointer to a DWORD that receives the number of output results.

Return Values

GetEnumCount returns a HRESULT. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The method was successful.
E_HANDLE | The interface handle was invalid.
E_POINTER | The pdwTotal parameter did not point to a valid memory location.
None of the above | The HRESULT contains an error code corresponding to the last error.

Remarks

A single bidi request can have multiple results. After calling GetEnumCount, the application can call IBidiRequest::GetOutputData to select a particular result.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, IBidiRequest::GetOutputData


IBidiRequestContainer

[This is preliminary documentation and subject to change.]

The IBidiRequestContainer interface allows an application or other objects to compose and retrieve a list of bidi requests.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IBidiRequestContainer Methods

Method | Description
AddRequest | Adds a request to the request list.
GetEnumObject | Enumerates the number of requests in the list.
GetRequestCount | Gets the number of requests in the list.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiRequestContainer::AddRequest

[This is preliminary documentation and subject to change.]

The IBidiRequestContainer::AddRequest method adds a request to the request list.

HRESULT IBidiRequestContainer::AddRequest(
  IBidiRequest *pRequest
)

Parameters

pRequest
[in] Pointer to the IBidiRequest interface.

Return Values

AddRequest returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, IBidiRequest


IBidiRequestContainer::GetEnumObject

[This is preliminary documentation and subject to change.]

The IBidiRequestContainer::GetEnumObject method enumerates the bidi requests in a list.

HRESULT IBidiRequestContainer::GetEnumObject(
  IEnumUnknown **ppenum
);

Parameters

ppenum
[out] Pointer to the variable that receives a pointer to the IEnumUnknown interface that enumerates the bidi requests in the container.

Return Values

GetEnumObject returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Remarks

An application can call IEnumUnknown->Next to retrieve one or more IBidiRequest interfaces.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, IEnumUnknown


IBidiRequestContainer::GetRequestCount

[This is preliminary documentation and subject to change.]

The IBidiRequestContainer::GetRequestCount method gets the number of requests in the request list.

HRESULT IBidiRequestContainer::GetRequestCount(
  ULONG *puCount
);

Parameters

puCount
[out] Pointer to a ULONG that receives the number of requests.

Return Values

GetRequestCount returns a HRESULT value. It can return one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiSpl

[This is preliminary documentation and subject to change.]

The IBidiSpl interface allows an application or other objects to send a single bidi request or a list of bidi requests.

Methods in Vtable Order

IUnknown Methods

QueryInterface
AddRef
Release

IBidiSpl Methods

Method | Description
BindDevice | Binds a printer to a bidi request.
UnbindDevice | Unbinds a printer.
SendRecv | Sends a bidi request.
MultiSendRecv | Sends a list of bidi requests.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiSpl::BindDevice

[This is preliminary documentation and subject to change.]

The IBidiSpl::BindDevice method binds a printer to a bidi request. This method is similar to the OpenPrinter function.

HRESULT IBidiSpl::BindDevice(
  const LPCWSTR pszDeviceName,
  const DWORD   dwAccess
);

Parameters

pszDeviceName
[in] Pointer to a NULL-terminated string that contains name of the printer or print server. If NULL, it indicates the local printer server.
dwAccess
[in] Access privileges for the printer. It can be one of the following values.
Value | Meaning
BIDI_ACCESS_ADMINISTRATOR | Permits users to perform all administrative tasks and basic printing operations except for SYNCHRONIZE. This is the same as PRINTER_ALL_ACCESS in OpenPrinter.
BIDI_ACCESS_USER | Permits users to perform basic printing operations. This is the same as PRINTER_ACCESS_USE in OpenPrinter.

Return Values

BindDevice returns a HRESULT value. It can be one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, OpenPrinter


IBidiSpl::UnbindDevice

[This is preliminary documentation and subject to change.]

The IBidiSpl::UnbindDevice method unbinds a printer from a bidi request. This method is similar to the ClosePrinter function.

HRESULT IBidiSpl::UnbindDevice (VOID);

Parameters

There are no parameters for this method.

Return Values

UnbindDevice returns a HRESULT value. It can be one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces, ClosePrinter


IBidiSpl::SendRecv

[This is preliminary documentation and subject to change.]

The IBidiSpl::SendRecv method sends a bidi request to the printer.

HRESULT IBidiSpl::SendRecv (
  const LPCWSTR pszAction,
  IBidiRequest *pRequest
);

Parameters

pszAction
[in] Pointer to a NULL-terminated string that specifies the action for this bidi request. It can be one of the following constants.
Constant | Value | Meaning
BIDI_ACTION_ENUM_SCHEMA | L"EnumSchema" | Enumerate the schema. The returned data will be a list of schema that the port monitor or print provider supports.
BIDI_ACTION_GET | L"Get" | Get the value of a specified schema.
BIDI_ACTION_GET_ALL | L"GetAll" | Get the values of all child nodes of the specified schema.
BIDI_ACTION_SET | L"Set" | Set a value of the schema.

pRequest
[in] Pointer to a single bidi request.

Return Values

This method returns a HRESULT value. It can be one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Note that the returned HRESULT may contain a Win32 error code defined in Bidi Error Codes.

Remarks

The BIDI_ACTION_* values are case insensitive strings.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


IBidiSpl::MultiSendRecv

[This is preliminary documentation and subject to change.]

The IBidiSpl::MultiSendRecv method sends a list of bidi requests.

HRESULT IBidiSpl::MultiSendRecv(
  const LPCWSTR   pszAction,
  IBidiRequestContainer  *pRequestContainer
)

Parameters

pszAction
[in] Pointer to a NULL-terminated string that specifies the action for this bidi request. It can be one of the following constants.
Constant | Value | Meaning
BIDI_ACTION_ENUM_SCHEMA | L"EnumSchema" | Enumerate the schema. The returned data will be a list of schema that the port monitor or print provider supports.
BIDI_ACTION_GET | L"Get" | Get the value of a specified schema.
BIDI_ACTION_GET_ALL | L"GetAll" | Get the values of all child nodes of the specified schema.
BIDI_ACTION_SET | L"Set" | Set a value of the schema.

pRequestContainer
[in] Pointer to the list of bidi requests.

Return Values

MultiSendRecv returns a HRESULT value. It can be one of the following values. For more information about COM error codes, see Error Handling.

Value | Meaning
S_OK | The operation was successfully carried out.
E_HANDLE | The interface handle was invalid.
None of the above | The HRESULT contains an error code corresponding to the last error.

Note that the returned HRESULT may contain a win32 error code defined in Bidi Error Codes.

Remarks

The BIDI_ACTION_* values are case insensitive strings.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Bidispl.h.

See Also

Printing and Print Spooler Overview, Printing and Print Spooler Interfaces,


Bidi Error Codes

[This is preliminary documentation and subject to change.]

The following error codes are used in Bidi Communication.

Value | Meaning
ERROR_BIDI_DEVICE_OFFLINE | The bidi call is supported but the connection to the remote printer is not available.
ERROR_BIDI_ERROR_BASE | The bidi call completed successfully, but there are one or more errors in the individual responses.
ERROR_BIDI_NOT_SUPPORTED | The bidi call is not supported by the port monitor or print provider.
ERROR_BIDI_SCHEMA_NOT_SUPPORTED | A caller tried to access a bidi schema that is not supported by the port monitor or the print provider
ERROR_BIDI_SCHEMA_READ_ONLY | A caller tried to set a readonly attribute.
ERROR_BIDI_SERVER_OFFLINE | The bidi call is supported but the connection to the remote printer server is not available.
ERROR_BIDI_STATUS_OK | The bidi call completed successfully.
ERROR_BIDI_STATUS_WARNING | The bidi call completed successfully, but there are one or more errors in the individual responses.


Rectangles

Win32®-based applications use rectangles to specify rectangular areas on the screen or in a window.

  • About Rectangles
  • Using Rectangles
  • Rectangle Reference


About Rectangles

In Win32®-based applications, rectangles are used for the cursor clipping region, the invalid portion of the client area, an area for displaying formatted text, or the scroll area. Your applications can also use rectangles to fill, frame, or invert a portion of the client area with a given brush, and to retrieve the coordinates of a window or a window's client area.

  • Rectangle Coordinates
  • Rectangle Operations


Rectangle Coordinates

An application must use a RECT structure to define a rectangle. The structure specifies the coordinates of two points: the upper left and lower right corners of the rectangle. The sides of the rectangle extend from these two points and are parallel to the x- and y-axes.

The coordinate values for a rectangle are expressed as signed integers. The coordinate value of a rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.

Because applications can use rectangles for many different purposes, the Win32 rectangle functions do not use an explicit unit of measure. Instead, all rectangle coordinates and dimensions are given in signed, logical values. The mapping mode and the function in which the rectangle is used determine the units of measure. For more information about coordinates and mapping modes, see Coordinate Spaces and Transformations.


Rectangle Operations

The Microsoft® Win32® application programming interface (API) provides several functions for working with rectangles.

The SetRect function creates a rectangle, the CopyRect function makes a copy of a given rectangle, and the SetRectEmpty function creates an empty rectangle. An empty rectangle is any rectangle that has zero width, zero height, or both. The IsRectEmpty function determines whether a given rectangle is empty. The EqualRect function determines whether two rectangles are identical — that is, whether they have the same coordinates.

The InflateRect function increases or decreases the width or height of a rectangle, or both. It can add or remove width from both ends of the rectangle; it can add or remove height from both the top and bottom of the rectangle.

The OffsetRect function moves a rectangle by a given amount. It moves the rectangle by adding the given x-amount, y-amount, or x- and y-amounts to the corner coordinates.

The PtInRect function determines whether a given point lies within a given rectangle. The point is in the rectangle if it lies on the left or top side or is completely within the rectangle. The point is not in the rectangle if it lies on the right or bottom side.

The IntersectRect function creates a new rectangle that is the intersection of two existing rectangles, as shown in the following figure.

The UnionRect function creates a new rectangle that is the union of two existing rectangles, as shown in the following figure.

For information about functions that draw ellipses and polygons, see Filled Shapes.


Using Rectangles

The example in this section illustrates how to use the rectangle functions. It consists of the main window procedure from an application that enables the user to move and size a bitmap.

When the application starts, it draws a 32-pixel by 32-pixel bitmap in the upper left corner of the screen. The user can move the bitmap by dragging it. To size the bitmap, the user creates a target rectangle by dragging the mouse, then drags the bitmap and "drops" it on the target rectangle. The application responds by copying the bitmap into the target rectangle.

The window procedure that allows the user to move and size the bitmap is given in the following example.

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hdc;                 // device context (DC) for window
    RECT rcTmp;              // temporary rectangle
    PAINTSTRUCT ps;          // paint data for BeginPaint and EndPaint
    POINT ptClientUL;        // client area upper left corner
    POINT ptClientLR;        // client area lower right corner
    static HDC hdcCompat;    // DC for copying bitmap
    static POINT pt;         // x and y coordinates of cursor
    static RECT rcBmp;       // rectangle that encloses bitmap
    static RECT rcTarget;    // rectangle to receive bitmap
    static RECT rcClient;    // client-area rectangle
    static BOOL fDragRect;   // TRUE if bitmap rect. is dragged
    static HBITMAP hbmp;     // handle of bitmap to display
    static HBRUSH hbrBkgnd;  // handle of background-color brush
    static COLORREF crBkgnd; // color of client-area background
    static HPEN hpenDot;     // handle of dotted pen

    switch (uMsg)
    {
        case WM_CREATE:

            // Load the bitmap resource.

            hbmp = LoadBitmap(hinst, MAKEINTRESOURCE(1));

            // Create a device context (DC) to hold the bitmap.
            // The bitmap is copied from this DC to the window's DC
            // whenever it must be drawn.

            hdc = GetDC(hwnd);
            hdcCompat = CreateCompatibleDC(hdc);
            SelectObject(hdcCompat, hbmp);

            // Create a brush of the same color as the background
            // of the client area. The brush is used later to erase
            // the old bitmap before copying the bitmap into the
            // target rectangle.

            crBkgnd = GetBkColor(hdc);
            hbrBkgnd = CreateSolidBrush(crBkgnd);
            ReleaseDC(hwnd, hdc);

            // Create a dotted pen. The pen is used to draw the
            // bitmap rectangle as the user drags it.

            hpenDot = CreatePen(PS_DOT, 1, RGB(0, 0, 0));

            // Set the initial rectangle for the bitmap. Note that
            // this application supports only a 32- by 32-pixel
            // bitmap. The rectangle is slightly larger than the
            // bitmap.

            SetRect(&rcBmp, 1, 1, 34, 34);
            return 0;

        case WM_PAINT:

            // Draw the bitmap rectangle and copy the bitmap into
            // it. The 32-pixel by 32-pixel bitmap is centered
            // in the rectangle by adding 1 to the left and top
            // coordinates of the bitmap rectangle, and subtracting 2
            // from the right and bottom coordinates.

            BeginPaint(hwnd, &ps);
            Rectangle(ps.hdc, rcBmp.left, rcBmp.top,
                rcBmp.right, rcBmp.bottom);
            StretchBlt(ps.hdc, rcBmp.left + 1, rcBmp.top + 1,
                (rcBmp.right - rcBmp.left) - 2,
                (rcBmp.bottom - rcBmp.top) - 2, hdcCompat,
                0, 0, 32, 32, SRCCOPY);
            EndPaint(hwnd, &ps);
            break;

        case WM_MOVE:
        case WM_SIZE:

            // Convert the client coordinates of the client-area
            // rectangle to screen coordinates and save them in a
            // rectangle. The rectangle is passed to the ClipCursor
            // function during WM_LBUTTONDOWN processing.

            GetClientRect(hwnd, &rcClient);
            ptClientUL.x = rcClient.left;
            ptClientUL.y = rcClient.top;
            ptClientLR.x = rcClient.right;
            ptClientLR.y = rcClient.bottom;
            ClientToScreen(hwnd, &ptClientUL);
            ClientToScreen(hwnd, &ptClientLR);
            SetRect(&rcClient, ptClientUL.x, ptClientUL.y,
                ptClientLR.x, ptClientLR.y);
            return 0;

        case WM_LBUTTONDOWN:

            // Restrict the mouse cursor to the client area. This
            // ensures that the window receives a matching
            // WM_LBUTTONUP message.

            ClipCursor(&rcClient);

            // Save the coordinates of the mouse cursor.

            pt.x = (LONG) LOWORD(lParam);
            pt.y = (LONG) HIWORD(lParam);

            // If the user has clicked the bitmap rectangle, redraw
            // it using the dotted pen. Set the fDragRect flag to
            // indicate that the user is about to drag the rectangle.

            if (PtInRect(&rcBmp, pt))
            {
                hdc = GetDC(hwnd);
                SelectObject(hdc, hpenDot);
                Rectangle(hdc, rcBmp.left, rcBmp.top, rcBmp.right,
                    rcBmp.bottom);
                fDragRect = TRUE;
                ReleaseDC(hwnd, hdc);
            }
            return 0;

        case WM_MOUSEMOVE:

            // Draw a target rectangle or drag the bitmap rectangle,
            // depending on the status of the fDragRect flag.

            if ((wParam && MK_LBUTTON)
                    && !fDragRect)
            {
                // Set the mix mode so that the pen color is the
                // inverse of the background color. The previous
                // rectangle can then be erased by drawing
                // another rectangle on top of it.

                hdc = GetDC(hwnd);
                SetROP2(hdc, R2_NOTXORPEN);

                // If a previous target rectangle exists, erase
                // it by drawing another rectangle on top of it.

                if (!IsRectEmpty(&rcTarget))
                {
                    Rectangle(hdc, rcTarget.left, rcTarget.top,
                        rcTarget.right, rcTarget.bottom);
                }

                // Save the coordinates of the target rectangle. Avoid
                // invalid rectangles by ensuring that the value of
                // the left coordinate is greater than that of the
                // right coordinate, and that the value of the bottom
                // coordinate is greater than that of the top.

                if ((pt.x < (LONG) LOWORD(lParam)) &&
                        (pt.y > (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, pt.x, HIWORD(lParam),
                        LOWORD(lParam), pt.y);
                }
                else if ((pt.x > (LONG) LOWORD(lParam)) &&
                        (pt.y > (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, LOWORD(lParam),
                        HIWORD(lParam), pt.x, pt.y);
                }
                else if ((pt.x > (LONG) LOWORD(lParam)) &&
                        (pt.y < (LONG) HIWORD(lParam)))
                {
                    SetRect(&rcTarget, LOWORD(lParam), pt.y,
                        pt.x, HIWORD(lParam));
                }
                else
                {
                    SetRect(&rcTarget, pt.x, pt.y, LOWORD(lParam),
                        HIWORD(lParam));
                }

                // Draw the new target rectangle.

                Rectangle(hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom);
                ReleaseDC(hwnd, hdc);
            }
            else if ((wParam && MK_LBUTTON)
                    && fDragRect)
            {

                // Set the mix mode so that the pen color is the
                // inverse of the background color.

                hdc = GetDC(hwnd);
                SetROP2(hdc, R2_NOTXORPEN);

                // Select the dotted pen into the DC and erase
                // the previous bitmap rectangle by drawing
                // another rectangle on top of it.

                SelectObject(hdc, hpenDot);
                Rectangle(hdc, rcBmp.left, rcBmp.top,
                    rcBmp.right, rcBmp.bottom);

                // Set the new coordinates of the bitmap rectangle,
                // then redraw it.

                OffsetRect(&rcBmp, LOWORD(lParam) - pt.x,
                    HIWORD(lParam) - pt.y);
                Rectangle(hdc, rcBmp.left, rcBmp.top,
                    rcBmp.right, rcBmp.bottom);
                ReleaseDC(hwnd, hdc);

                // Save the coordinates of the mouse cursor.

                pt.x = (LONG) LOWORD(lParam);
                pt.y = (LONG) HIWORD(lParam);
            }
            return 0;

        case WM_LBUTTONUP:

            // If the bitmap rectangle and target rectangle
            // intersect, copy the bitmap into the target
            // rectangle. Otherwise, copy the bitmap into the
            // rectangle bitmap at its new location.

            if (IntersectRect(&rcTmp, &rcBmp, &rcTarget))
            {

                // Erase the bitmap rectangle by filling it with
                // the background color.

                hdc = GetDC(hwnd);
                FillRect(hdc, &rcBmp, hbrBkgnd);

                // Redraw the target rectangle because the part
                // that intersected with the bitmap rectangle was
                // erased by the call to FillRect.

                Rectangle(hdc, rcTarget.left, rcTarget.top,
                    rcTarget.right, rcTarget.bottom);

                // Copy the bitmap into the target rectangle.

                StretchBlt(hdc, rcTarget.left + 1, rcTarget.top + 1,
                    (rcTarget.right - rcTarget.left) - 2,
                    (rcTarget.bottom - rcTarget.top) - 2, hdcCompat,
                    0, 0, 32, 32, SRCCOPY);

                // Copy the target rectangle to the bitmap
                // rectangle, set the coordinates of the target
                // rectangle to 0, then reset the fDragRect flag.

                CopyRect(&rcBmp, &rcTarget);
                SetRectEmpty(&rcTarget);
                ReleaseDC(hwnd, hdc);
                fDragRect = FALSE;
            }

            else if (fDragRect)
            {

                // Draw the bitmap rectangle, copy the bitmap into
                // it, and reset the fDragRect flag.

                hdc = GetDC(hwnd);
                Rectangle(hdc, rcBmp.left, rcBmp.top,
                    rcBmp.right, rcBmp.bottom);
                StretchBlt(hdc, rcBmp.left + 1, rcBmp.top + 1,
                    (rcBmp.right - rcBmp.left) - 2,
                    (rcBmp.bottom - rcBmp.top) - 2, hdcCompat,
                    0, 0, 32, 32, SRCCOPY);
                ReleaseDC(hwnd, hdc);
                fDragRect = FALSE;
            }

            // Release the mouse cursor.

            ClipCursor((LPRECT) NULL);
            return 0;

        case WM_DESTROY:

            // Destroy the background brush, compatible bitmap,
            // and the bitmap.

            DeleteObject(hbrBkgnd);
            DeleteDC(hdcCompat);
            DeleteObject(hbmp);
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return (LRESULT) NULL;
}


Rectangle Reference

The following elements are used with rectangles:

  • Rectangle Functions
  • Rectangle Structures
  • Rectangle Macros


Rectangle Functions

The following functions are used with rectangles.

Function | Description
CopyRect | Copies the coordinates of one rectangle to another.
EqualRect | Determines whether the two specified rectangles are equal by comparing the coordinates of their upper-left and lower-right corners.
InflateRect | Increases or decreases the width and height of the specified rectangle.
IntersectRect | Calculates the intersection of two source rectangles and places the coordinates of the intersection rectangle into the destination rectangle.
IsRectEmpty | Determines whether the specified rectangle is empty.
OffsetRect | Moves the specified rectangle by the specified offsets.
PtInRect | Determines whether the specified point lies within the specified rectangle.
SetRect | Sets the coordinates of the specified rectangle.
SetRectEmpty | Creates an empty rectangle in which all coordinates are set to zero.
SubtractRect | Determines the coordinates of a rectangle formed by subtracting one rectangle from another.
UnionRect | Creates the union of two rectangles.


CopyRect

The CopyRect function copies the coordinates of one rectangle to another.

BOOL CopyRect(
  LPRECT lprcDst,      // destination rectangle
  CONST RECT* lprcSrc  // source rectangle
);

Parameters

lprcDst
[out] Pointer to the RECT structure that receives the logical coordinates of the source rectangle.
lprcSrc
[in] Pointer to the RECT structure whose coordinates are to be copied in logical units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, RECT, SetRect, SetRectEmpty


EqualRect

The EqualRect function determines whether the two specified rectangles are equal by comparing the coordinates of their upper-left and lower-right corners.

BOOL EqualRect(
  CONST RECT *lprc1,  // first rectangle
  CONST RECT *lprc2   // second rectangle
);

Parameters

lprc1
[in] Pointer to a RECT structure that contains the logical coordinates of the first rectangle.
lprc2
[in] Pointer to a RECT structure that contains the logical coordinates of the second rectangle.

Return Values

If the two rectangles are identical, the return value is nonzero.

If the two rectangles are not identical, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, IsRectEmpty, PtInRect, RECT


InflateRect

The InflateRect function increases or decreases the width and height of the specified rectangle. The InflateRect function adds dx units to the left and right ends of the rectangle and dy units to the top and bottom. The dx and dy parameters are signed values; positive values increase the width and height, and negative values decrease them.

BOOL InflateRect(
  LPRECT lprc,  // rectangle
  int dx,       // amount to adjust width
  int dy        // amount to adjust height
);

Parameters

lprc
[in/out] Pointer to the RECT structure that increases or decreases in size.
dx
[in] Specifies the amount to increase or decrease the rectangle width. This parameter must be negative to decrease the width.
dy
[in] Specifies the amount to increase or decrease the rectangle height. This parameter must be negative to decrease the height.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, IntersectRect, OffsetRect, RECT, UnionRect


IntersectRect

The IntersectRect function calculates the intersection of two source rectangles and places the coordinates of the intersection rectangle into the destination rectangle. If the source rectangles do not intersect, an empty rectangle (in which all coordinates are set to zero) is placed into the destination rectangle.

BOOL IntersectRect(
  LPRECT lprcDst,        // intersection buffer
  CONST RECT *lprcSrc1,  // first rectangle
  CONST RECT *lprcSrc2   // second rectangle
);

Parameters

lprcDst
[out] Pointer to the RECT structure that is to receive the intersection of the rectangles pointed to by the lprcSrc1 and lprcSrc2 parameters. This parameter cannot be NULL.
lprcSrc1
[in] Pointer to the RECT structure that contains the first source rectangle.
lprcSrc2
[in] Pointer to the RECT structure that contains the second source rectangle.

Return Values

If the rectangles intersect, the return value is nonzero.

If the rectangles do not intersect, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, InflateRect, OffsetRect, RECT, UnionRect


IsRectEmpty

The IsRectEmpty function determines whether the specified rectangle is empty. A empty rectangle is one that has no area; that is, the coordinate of the right side is less than or equal to the coordinate of the left side, or the coordinate of the bottom side is less than or equal to the coordinate of the top side.

BOOL IsRectEmpty(
  CONST RECT *lprc   // rectangle
);

Parameters

lprc
[in] Pointer to a RECT structure that contains the logical coordinates of the rectangle.

Return Values

If the rectangle is empty, the return value is nonzero.

If the rectangle is not empty, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, EqualRect, PtInRect, RECT


OffsetRect

The OffsetRect function moves the specified rectangle by the specified offsets.

BOOL OffsetRect(
  LPRECT lprc,  // rectangle
  int dx,       // horizontal offset
  int dy        // vertical offset
);

Parameters

lprc
[in/out] Pointer to a RECT structure that contains the logical coordinates of the rectangle to be moved.
dx
[in] Specifies the amount to move the rectangle left or right. This parameter must be a negative value to move the rectangle to the left.
dy
[in] Specifies the amount to move the rectangle up or down. This parameter must be a negative value to move the rectangle up.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, InflateRect, IntersectRect, UnionRect, RECT


PtInRect

The PtInRect function determines whether the specified point lies within the specified rectangle. A point is within a rectangle if it lies on the left or top side or is within all four sides. A point on the right or bottom side is considered outside the rectangle.

BOOL PtInRect(
  CONST RECT *lprc,  // rectangle
  POINT pt           // point
);

Parameters

lprc
[in] Pointer to a RECT structure that contains the specified rectangle.
pt
[in] Specifies a POINT structure that contains the specified point.

Return Values

If the specified point lies within the rectangle, the return value is nonzero.

If the specified point does not lie within the rectangle, the return value is zero.

Remarks

The rectangle must be normalized before PtInRect is called. That is, lprc.right must be greater than lprc.left and lprc.bottom must be greater than lprc.top. If the rectangle is not normalized, a point is never considered inside of the rectangle.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, EqualRect, IsRectEmpty, POINT, RECT


SetRect

The SetRect function sets the coordinates of the specified rectangle. This is equivalent to assigning the left, top, right, and bottom arguments to the appropriate members of the RECT structure.

BOOL SetRect(
  LPRECT lprc, // rectangle
  int xLeft,   // left side
  int yTop,    // top side
  int xRight,  // right side
  int yBottom  // bottom side
);

Parameters

lprc
[out] Pointer to the RECT structure that contains the rectangle to be set.
xLeft
[in] Specifies the x-coordinate of the rectangle's upper-left corner.
yTop
[in] Specifies the y-coordinate of the rectangle's upper-left corner.
xRight
[in] Specifies the x-coordinate of the rectangle's lower-right corner.
yBottom
[in] Specifies the y-coordinate of the rectangle's lower-right corner.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, CopyRect, SetRectEmpty, RECT


SetRectEmpty

The SetRectEmpty function creates an empty rectangle in which all coordinates are set to zero.

BOOL SetRectEmpty(
  LPRECT lprc   // rectangle
);

Parameters

lprc
[out] Pointer to the RECT structure that contains the coordinates of the rectangle.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

For an example see, Using Rectangles.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, CopyRect, RECT, SetRect


SubtractRect

The SubtractRect function determines the coordinates of a rectangle formed by subtracting one rectangle from another.

BOOL SubtractRect(
  LPRECT lprcDst,        // destination rectangle
  CONST RECT *lprcSrc1,  // first rectangle
  CONST RECT *lprcSrc2   // second rectangle
);

Parameters

lprcDst
[out] Pointer to a RECT structure that receives the coordinates of the rectangle determined by subtracting the rectangle pointed to by lprcSrc2 from the rectangle pointed to by lprcSrc1.
lprcSrc1
[in] Pointer to a RECT structure from which the function subtracts the rectangle pointed to by lprcSrc2.
lprcSrc2
[in] Pointer to a RECT structure that the function subtracts from the rectangle pointed to by lprcSrc1.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The function only subtracts the rectangle specified by lprcSrc2 from the rectangle specified by lprcSrc1 when the rectangles intersect completely in either the x- or y-direction. For example, if *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 has the coordinates (50,50,150,150), the function sets the coordinates of the rectangle pointed to by lprcDst to (10,10,100,100). If *lprcSrc1 has the coordinates (10,10,100,100) and *lprcSrc2 has the coordinates (50,10,150,150), however, the function sets the coordinates of the rectangle pointed to by lprcDst to (10,10,50,100).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, IntersectRect, RECT, UnionRect


UnionRect

The UnionRect function creates the union of two rectangles. The union is the smallest rectangle that contains both source rectangles.

BOOL UnionRect(
  LPRECT lprcDst,        // destination rectangle
  CONST RECT *lprcSrc1,  // first rectangle
  CONST RECT *lprcSrc2   // second rectangle
);

Parameters

lprcDst
[out] Pointer to the RECT structure that will receive a rectangle containing the rectangles pointed to by the lprcSrc1 and lprcSrc2 parameters.
lprcSrc1
[in] Pointer to the RECT structure that contains the first source rectangle.
lprcSrc2
[in] Pointer to the RECT structure that contains the second source rectangle.

Return Values

If the specified structure contains a nonempty rectangle, the return value is nonzero.

If the specified structure does not contain a nonempty rectangle, the return value is zero.

Windows NT/2000 or later: To get extended error information, call GetLastError.

Remarks

The system ignores the dimensions of an empty rectangle — that is, a rectangle in which all coordinates are set to zero, so that it has no height or no width.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

Rectangles Overview, Rectangle Functions, InflateRect, IntersectRect, OffsetRect, RECT


Rectangle Structures

The following structures are used with rectangles.

POINT
POINTS
RECT


POINT

The POINT structure defines the x- and y- coordinates of a point.

typedef struct tagPOINT {
  LONG x;
  LONG y;
} POINT, *PPOINT;

Members

x
Specifies the x-coordinate of the point.
y
Specifies the y-coordinate of the point.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Structures, ChildWindowFromPoint, GetBrushOrgEx, PtInRect, SetBrushOrgEx, WindowFromPoint


POINTS

The POINTS structure defines the coordinates of a point.

typedef struct tagPOINTS {
  SHORT x;
  SHORT y;
} POINTS, *PPOINTS;

Members

x
Specifies the x-coordinate of the point.
y
Specifies the y-coordinate of the point.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Structures, ChildWindowFromPoint, PtInRect, WindowFromPoint, POINT


RECT

The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.

typedef struct _RECT {
  LONG left;
  LONG top;
  LONG right;
  LONG bottom;
} RECT, *PRECT;

Members

left
Specifies the x-coordinate of the upper-left corner of the rectangle.
top
Specifies the y-coordinate of the upper-left corner of the rectangle.
right
Specifies the x-coordinate of the lower-right corner of the rectangle.
bottom
Specifies the y-coordinate of the lower-right corner of the rectangle.

Remarks

When RECT is passed to the FillRect function, the rectangle is filled up to, but not including, the right column and bottom row of pixels. This structure is identical to the RECTL structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Windef.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Structures, FillRect, RECTL, SMALL_RECT


Rectangle Macros

The following macros are used with rectangles.

MAKEPOINTS
POINTSTOPOINT
POINTTOPOINTS


MAKEPOINTS

The MAKEPOINTS macro converts a value that contains the x- and y-coordinates of a point into a POINTS structure.

POINTS MAKEPOINTS(
  DWORD dwValue  // coordinates of a point
);

Parameters

dwValue
Specifies the coordinates of a point. The x-coordinate is in the low-order word, and the y-coordinate is in the high-order word.

Return Values

The return value is a pointer to a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Macros, GetMessagePos


POINTSTOPOINT

The POINTSTOPOINT macro copies the contents of a POINTS structure into a POINT structure.

POINTSTOPOINT(
  POINT pt,  // POINT structure
  POINTS pts // POINTS structure
);

Parameters

pt
Specifies the POINT structure to receive the contents of the POINTS structure.
pts
Specifies the POINTS structure to copy.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Macros, MAKEPOINTS, POINTTOPOINTS


POINTTOPOINTS

The POINTTOPOINTS macro converts a POINT structure to a POINTS structure.

POINTS POINTTOPOINTS(
  POINT pt  // coordinates of a point
);

Parameters

pt
Specifies the POINT structure to convert.

Return Values

The return value is a POINTS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Rectangles Overview, Rectangle Macros, MAKEPOINTS, POINT, POINTS


Regions

A region is a rectangle, polygon, or ellipse (or a combination of two or more of these shapes) that can be filled, painted, inverted, framed, and used to perform hit testing (testing for the cursor location).

  • About Regions
  • Using Regions
  • Region Reference


About Regions

Following are three types of regions that have been filled and framed.

  • Region Creation and Selection
  • Region Operations


Region Creation and Selection

An application creates a region by calling a function associated with a specific shape. The following table shows the function(s) associated with each of the standard shapes.

Shape | Function
Rectangular region | CreateRectRgn, CreateRectRgnIndirect, SetRectRgn
Rectangular region with rounded corners | CreateRoundRectRgn
Elliptical region | CreateEllipticRgn, CreateEllipticRgnIndirect
Polygonal region | CreatePolygonRgn, CreatePolyPolygonRgn

Each region creation function returns a handle that identifies the new region. An application can use this handle to select the region into a device context by calling the SelectObject function and supplying this handle as the second argument. After a region is selected into a device context, the application can perform various operations on it.


Region Operations

Applications can combine regions, compare them, paint or invert their interiors, draw a frame around them, retrieve their dimensions, and test whether the cursor lies within their boundaries.

  • Combining Regions
  • Comparing Regions
  • Filling Regions
  • Painting Regions
  • Inverting Regions
  • Framing Regions
  • Retrieving a Bounding Rectangle
  • Moving Regions
  • Hit Testing Regions


Combining Regions

An application combines two regions by calling the CombineRgn function. Using this function, an application can combine the intersecting parts of two regions, all but the intersecting parts of two regions, the two original regions in their entirety, and so on. Following are five values that define the region combinations.

Value | Meaning
RGN_AND | The intersecting parts of two original regions define a new region.
RGN_COPY | A copy of the first (of the two original regions) defines a new region.
RGN_DIFF | The part of the first region that does not intersect the second defines a new region.
RGN_OR | The two original regions define a new region.
RGN_XOR | Those parts of the two original regions that do not overlap define a new region.

The following illustration shows the five possible combinations of a square and a circular region resulting from a call to CombineRgn.


Comparing Regions

An application compares two regions to determine whether or not they are identical by calling the EqualRgn function. EqualRgn considers two regions identical if they are equal in size and shape.


Filling Regions

An application fills the interior of a region by calling the FillRgn function and supplying a handle that identifies a specific brush. When an application calls FillRgn, the system fills the region with the brush by using the current fill mode for the specified device context. There are two fill modes: alternate and winding. The application can set the fill mode for a device context by calling the SetPolyFillMode function. The application can retrieve the current fill mode for a device context by calling the GetPolyFillMode function.

The following illustration shows two identical regions: one filled using alternate mode and the other filled using winding mode.

Alternate Mode

To determine which pixels the system highlights when alternate mode is specified, perform the following test:

  1. Select a pixel within the region's interior.
  2. Draw an imaginary ray, in the positive x-direction, from that pixel towards infinity.
  3. Each time the ray intersects a boundary line, increment a count value.

The system highlights the pixel if the count value is an odd number.

Winding Mode

To determine which pixels the system highlights when winding mode is specified, perform the following test:

  1. Determine the direction in which each boundary line is drawn.
  2. Select a pixel within the region's interior.
  3. Draw an imaginary ray, in the positive x-direction, from the pixel toward infinity.
  4. Each time the ray intersects a boundary line with a positive y-component, increment a count value. Each time the ray intersects a boundary line with a negative y-component, decrement the count value.

The system highlights the pixel if the count value is nonzero.


Painting Regions

An application fills the interior of a region by using the brush currently selected into a device context by the PaintRgn function. This function uses the current polygon fill modes (alternate and winding).


Inverting Regions

An application inverts the colors that appear within a region by calling the InvertRgn function. On monochrome displays, InvertRgn makes white pixels black and black pixels white. On color screens, this inversion is dependent on the type of technology used to generate the colors for the screen.


Framing Regions

An application draws a border around a region by calling the FrameRgn function and specifying the border width and brush pattern that the system uses when drawing the frame.


Retrieving a Bounding Rectangle

An application retrieves the dimensions of a region's bounding rectangle by calling the GetRgnBox function. If the region is rectangular, GetRgnBox returns the dimensions of the region. If the region is elliptical, the function returns the dimensions of the smallest rectangle that can be drawn around the ellipse. The long sides of the rectangle are the same length as the ellipse's major axis, and the short sides of the rectangle are the same length as the ellipse's minor axis. If the region is polygonal, GetRgnBox returns the dimensions of the smallest rectangle that can be drawn around the entire polygon.


Moving Regions

An application moves a region by calling the OffsetRgn function. The given offsets along the x-axis and y-axis determine the number of logical units to move left or right and up or down.


Hit Testing Regions

An application performs hit testing on regions to determine the coordinates of the current cursor position. Then it passes these coordinates — as well as a handle identifying the region — to the PtInRegion function. The cursor coordinates can be retrieved by processing the various mouse messages, such as WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, and WM_RBUTTONUP. The return value for PtInRegion indicates whether the cursor position is within the given region.


Using Regions

  • Using regions to clip output
  • Using regions to perform hit testing


Using Regions to Clip Output

This section contains a single example that demonstrates how you can use regions to enable the user to define how a part of client area output can appear. Regions used for this purpose are called clipping regions.

The example for this section is taken from a Win32-based application that enables a user to capture the entire desktop as a bitmap and then isolate and save a part of this image as a .BMP file.

By clicking Define Clip Region from the application's menu, the user is able to select a clipping region by clicking the left mouse button and dragging the mouse. As the user drags the mouse, the application draws a rectangle that corresponds to the new clipping region.

By clicking Clip from the application's menu, the user is able to redraw the isolated part of the image within the boundaries of the specified rectangle.


Defining the Clipping Region

When the user clicks Define Clip Region, the system issues a WM_COMMAND message. The wParam parameter of this message contains an application-defined constant, IDM_DEFINE, that indicates that the user selected this option from the menu. The application processes this input by setting a Boolean flag, fDefineRegion, as shown in the following code sample.

case WM_COMMAND:
    switch (wParam)
    {

        case IDM_DEFINE:
            fDefineRegion = TRUE;
            break;

After clicking Define Clipping Region, the user can begin drawing the rectangle by clicking and dragging the mouse while the cursor is in the application's client area.

When the user presses the left button, the system issues a WM_LBUTTONDOWN message. The lParam parameter of this message contains the cursor coordinates, which correspond to the upper left corner of a rectangle used to define the clipping region. The application processes the WM_LBUTTONDOWN message, as follows.

// These variables are required for clipping.

static POINT ptUpperLeft;
static POINT ptLowerRight;
static POINT aptRect[5];
static POINT ptTmp;
static POINTS ptsTmp;
static BOOL fDefineRegion;
static BOOL fRegionExists;
static HRGN hrgn;
static RECT rctTmp;
int i;

switch (message)
{

    case WM_LBUTTONDOWN:
        if (fDefineRegion)
        {

        // Retrieve the new upper left corner.

            ptsTmp = MAKEPOINTS(lParam);
            ptUpperLeft.x = (LONG) ptsTmp.x;
            ptUpperLeft.y = (LONG) ptsTmp.y;
        }

        if (fRegionExists)
        {

            // Erase the previous rectangle.

            hdc = GetDC(hwnd);
            SetROP2(hdc, R2_NOTXORPEN);

            if (!Polyline(hdc, (CONST POINT *) aptRect, 5))
                errhandler("Polyline Failed", hwnd);
            ReleaseDC(hwnd, hdc);

            // Clear the rectangle coordinates.

            for (i = 0; i < 4; i++)
            {
                aptRect[i].x = 0;
                aptRect[i].y = 0;
            }

            // Clear the temporary point structure.

            ptTmp.x = 0;
            ptTmp.y = 0;

            // Clear the lower right coordinates.

            ptLowerRight.x = 0;
            ptLowerRight.y = 0;

            // Reset the flag.

            fRegionExists = FALSE;
            fDefineRegion = TRUE;

            // Retrieve the new upper left corner.

            ptsTmp = MAKEPOINTS(lParam);
            ptUpperLeft.x = (LONG) ptsTmp.x;
            ptUpperLeft.y = (LONG) ptsTmp.y;
        }
    break;
}

As the user drags the mouse, the system issues WM_MOUSEMOVE messages and stores the new cursor coordinates in the lParam parameter. Each time the application receives a new WM_MOUSEMOVE message, it erases the previous rectangle (if one exists) and draws the new rectangle by calling the Polyline function, passing it the coordinates of the four corners of the rectangle. The application performs the following tasks.

// These variables are required for clipping.

static POINT ptUpperLeft;
static POINT ptLowerRight;
static POINT aptRect[5];
static POINT ptTmp;
static POINTS ptsTmp;
static BOOL fDefineRegion;
static BOOL fRegionExists;
static HRGN hrgn;
static RECT rctTmp;
int i;

switch (message)
{

    case WM_MOUSEMOVE:

    if (wParam & MK_LBUTTON && fDefineRegion)
    {

        // Get a window DC.

        hdc = GetDC(hwnd);

        if (!SetROP2(hdc, R2_NOTXORPEN))
            errhandler("SetROP2 Failed", hwnd);

        // If previous mouse movement occurred, store the original
        // lower right corner coordinates in a temporary structure.

        if (ptLowerRight.x)
        {
            ptTmp.x = ptLowerRight.x;
            ptTmp.y = ptLowerRight.y;
        }

        // Get the new coordinates of the clipping region's lower
        // right corner.

        ptsTmp = MAKEPOINTS(lParam);
        ptLowerRight.x = (LONG) ptsTmp.x;
        ptLowerRight.y = (LONG) ptsTmp.y;

        // If previous mouse movement occurred, erase the original
        // rectangle.

        if (ptTmp.x)
        {
            aptRect[0].x = ptUpperLeft.x;
            aptRect[0].y = ptUpperLeft.y;
            aptRect[1].x = ptTmp.x;
            aptRect[1].y = ptUpperLeft.y;
            aptRect[2].x = ptTmp.x;
            aptRect[2].y = ptTmp.y;
            aptRect[3].x = ptUpperLeft.x;
            aptRect[3].y = ptTmp.y;
            aptRect[4].x = aptRect[0].x;
            aptRect[4].y = aptRect[0].y;

            if (!Polyline(hdc, (CONST POINT *) aptRect, 5))
                errhandler("Polyline Failed", hwnd);
        }

        aptRect[0].x = ptUpperLeft.x;
        aptRect[0].y = ptUpperLeft.y;
        aptRect[1].x = ptLowerRight.x;
        aptRect[1].y = ptUpperLeft.y;
        aptRect[2].x = ptLowerRight.x;
        aptRect[2].y = ptLowerRight.y;
        aptRect[3].x = ptUpperLeft.x;
        aptRect[3].y = ptLowerRight.y;
        aptRect[4].x = aptRect[0].x;
        aptRect[4].y = aptRect[0].y;

        if (!Polyline(hdc, (CONST POINT *) aptRect, 5))
             errhandler("Polyline Failed", hwnd);

        ReleaseDC(hwnd, hdc);
    }
    break;


Clipping Output

After the user clicks Clip from the menu, the application uses the coordinates of the rectangle the user created to define a clipping region. After defining the clipping region and selecting it into the application's device context, the application redraws the bitmapped image. The application performs these tasks, as follows.

// These variables are required for clipping.

static POINT ptUpperLeft;
static POINT ptLowerRight;
static POINT aptRect[5];
static POINT ptTmp;
static POINTS ptsTmp;
static BOOL fDefineRegion;
static BOOL fRegionExists;
static HRGN hrgn;
static RECT rctTmp;
int i;

case WM_COMMAND:
    switch (wParam)
    {

    case IDM_CLIP:

    hdc = GetDC(hwnd);

    // Retrieve the application's client rectangle and paint
    // with the default (white) brush.

    GetClientRect(hwnd, &rctTmp);
    FillRect(hdc, &rctTmp, GetStockObject(WHITE_BRUSH));

    // Use the rect coordinates to define a clipping region.

    hrgn = CreateRectRgn(aptRect[0].x, aptRect[0].y,
        aptRect[2].x, aptRect[2].y);
    SelectClipRgn(hdc, hrgn);

    // Transfer (draw) the bitmap into the clipped rectangle.

    BitBlt(hdc,
       0, 0,
       bmp.bmWidth, bmp.bmHeight,
       hdcCompatible,
       0, 0,
       SRCCOPY);

    ReleaseDC(hwnd, hdc);
    break;
    }


Using Regions to Perform Hit Testing

The example in Brushes uses regions to simulate a "zoomed" view of an 8- by 8-pixel monochrome bitmap. By clicking on the pixels in this bitmap, the user creates a custom brush suitable for drawing operations. The example shows how to use the PtInRegion function to perform hit testing and the InvertRgn function to invert the colors in a region.


Region Reference

The following elements are used with regions.

  • Region Functions
  • Region Structures


Region Functions

The following functions are used with regions.

Function | Description
CombineRgn | Combines two regions and stores the result in a third region.
CreateEllipticRgn | Creates an elliptical region.
CreateEllipticRgnIndirect | Creates an elliptical region.
CreatePolygonRgn | Creates a polygonal region.
CreatePolyPolygonRgn | Creates a region consisting of a series of polygons.
CreateRectRgn | Creates a rectangular region.
CreateRectRgnIndirect | Creates a rectangular region.
CreateRoundRectRgn | Creates a rectangular region with rounded corners.
EqualRgn | Checks the two specified regions to determine whether they are identical.
ExtCreateRegion | Creates a region from the specified region and transformation data.
FillRgn | Fills a region by using the specified brush.
FrameRgn | Draws a border around the specified region by using the specified brush.
GetPolyFillMode | Retrieves the current polygon fill mode.
GetRegionData | Fills the specified buffer with data describing a region.
GetRgnBox | Retrieves the bounding rectangle of the specified region.
InvertRgn | Inverts the colors in the specified region.
OffsetRgn | Moves a region by the specified offsets.
PaintRgn | Paints the specified region by using the brush currently selected into the device context.
PtInRegion | Determines whether the specified point is inside the specified region.
RectInRegion | Determines whether any part of the specified rectangle is within the boundaries of a region.
SetPolyFillMode | Sets the polygon fill mode for functions that fill polygons.
SetRectRgn | Converts a region into a rectangular region with the specified coordinates.


CombineRgn

The CombineRgn function combines two regions and stores the result in a third region. The two regions are combined according to the specified mode.

int CombineRgn(
  HRGN hrgnDest,      // handle to destination region
  HRGN hrgnSrc1,      // handle to source region
  HRGN hrgnSrc2,      // handle to source region
  int fnCombineMode   // region combining mode
);

Parameters

hrgnDest
[in] Handle to a new region with dimensions defined by combining two other regions. (This region must exist before CombineRgn is called.)
hrgnSrc1
[in] Handle to the first of two regions to be combined.
hrgnSrc2
[in] Handle to the second of two regions to be combined.
fnCombineMode
[in] Specifies a mode indicating how the two regions will be combined. This parameter can be one of the following values.
Value | Description
RGN_AND | Creates the intersection of the two combined regions.
RGN_COPY | Creates a copy of the region identified by hrgnSrc1.
RGN_DIFF | Combines the parts of hrgnSrc1 that are not part of hrgnSrc2.
RGN_OR | Creates the union of two combined regions.
RGN_XOR | Creates the union of two combined regions except for any overlapping areas.

Return Values

The return value specifies the type of the resulting region. It can be one of the following values.

Value | Meaning
NULLREGION | The region is empty.
SIMPLEREGION | The region is a single rectangle.
COMPLEXREGION | The region is more than a single rectangle.
ERROR | No region is created.

Remarks

The three regions need not be distinct. For example, the hrgnSrc1 parameter can equal the hrgnDest parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateEllipticRgn, CreateEllipticRgnIndirect, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn


CreateEllipticRgn

The CreateEllipticRgn function creates an elliptical region.

HRGN CreateEllipticRgn(
  int nLeftRect,   // x-coord of upper-left corner of rectangle
  int nTopRect,    // y-coord of upper-left corner of rectangle
  int nRightRect,  // x-coord of lower-right corner of rectangle
  int nBottomRect  // y-coord of lower-right corner of rectangle
);

Parameters

nLeftRect
[in] Specifies the x-coordinate in logical units, of the upper-left corner of the bounding rectangle of the ellipse.
nTopRect
[in] Specifies the y-coordinate in logical units, of the upper-left corner of the bounding rectangle of the ellipse.
nRightRect
[in] Specifies the x-coordinate in logical units, of the lower-right corner of the bounding rectangle of the ellipse.
nBottomRect
[in] Specifies the y-coordinate in logical units, of the lower-right corner of the bounding rectangle of the ellipse.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

A bounding rectangle defines the size, shape, and orientation of the region: The long sides of the rectangle define the length of the ellipse's major axis; the short sides define the length of the ellipse's minor axis; and the center of the rectangle defines the intersection of the major and minor axes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateEllipticRgnIndirect, DeleteObject, SelectObject


CreateEllipticRgnIndirect

The CreateEllipticRgnIndirect function creates an elliptical region.

HRGN CreateEllipticRgnIndirect(
  CONST RECT *lprc   // bounding rectangle
);

Parameters

lprc
[in] Pointer to a RECT structure that contains the coordinates of the upper-left and lower-right corners of the bounding rectangle of the ellipse in logical units.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

A bounding rectangle defines the size, shape, and orientation of the region: The long sides of the rectangle define the length of the ellipse's major axis; the short sides define the length of the ellipse's minor axis; and the center of the rectangle defines the intersection of the major and minor axes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateEllipticRgn, DeleteObject, RECT, SelectObject


CreatePolygonRgn

The CreatePolygonRgn function creates a polygonal region.

HRGN CreatePolygonRgn(
  CONST POINT *lppt,  // array of points
  int cPoints,        // number of points in array
  int fnPolyFillMode  // polygon-filling mode
);

Parameters

lppt
[in] Pointer to an array of POINT structures that define the vertices of the polygon in logical units. The polygon is presumed closed. Each vertex can be specified only once.
cPoints
[in] Specifies the number of points in the array.
fnPolyFillMode
[in] Specifies the fill mode used to determine which pixels are in the region. This parameter can be one of the following values.
Value | Meaning
ALTERNATE | Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING | Selects winding mode (fills any region with a nonzero winding value).

For more information about these modes, see the SetPolyFillMode function.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, GetRegionData, DeleteObject, POINT, SelectObject, SetPolyFillMode


CreatePolyPolygonRgn

The CreatePolyPolygonRgn function creates a region consisting of a series of polygons. The polygons can overlap.

HRGN CreatePolyPolygonRgn(
  CONST POINT *lppt,        // pointer to array of points
  CONST INT *lpPolyCounts,  // pointer to count of vertices
  int nCount,               // number of integers in array
  int fnPolyFillMode        // polygon fill mode
);

Parameters

lppt
[in] Pointer to an array of POINT structures that define the vertices of the polygons in logical units. The polygons are specified consecutively. Each polygon is presumed closed and each vertex is specified only once.
lpPolyCounts
[in] Pointer to an array of integers, each of which specifies the number of points in one of the polygons in the array pointed to by lppt.
nCount
[in] Specifies the total number of integers in the array pointed to by lpPolyCounts.
fnPolyFillMode
[in] Specifies the fill mode used to determine which pixels are in the region. This parameter can be one of the following values.
Value | Meaning
ALTERNATE | Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING | Selects winding mode (fills any region with a nonzero winding value).

For more information about these modes, see the SetPolyFillMode function.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, GetRegionData, DeleteObject, POINT, SelectObject, SetPolyFillMode


CreateRectRgn

The CreateRectRgn function creates a rectangular region.

HRGN CreateRectRgn(
  int nLeftRect,   // x-coordinate of upper-left corner
  int nTopRect,    // y-coordinate of upper-left corner
  int nRightRect,  // x-coordinate of lower-right corner
  int nBottomRect  // y-coordinate of lower-right corner
);

Parameters

nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the region in logical units.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the region in logical units.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the region in logical units.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the region in logical units.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

The region will be exclusive of the bottom and right edges.

For an example, see Drawing Markers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, GetRegionData, DeleteObject, SelectObject


CreateRectRgnIndirect

The CreateRectRgnIndirect function creates a rectangular region.

HRGN CreateRectRgnIndirect(
  CONST RECT *lprc   // rectangle
);

Parameters

lprc
[in] Pointer to a RECT structure that contains the coordinates of the upper-left and lower-right corners of the rectangle that defines the region in logical units.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

The region will be exclusive of the bottom and right edges.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRoundRectRgn, ExtCreateRegion, GetRegionData, DeleteObject, RECT, SelectObject


CreateRoundRectRgn

The CreateRoundRectRgn function creates a rectangular region with rounded corners.

HRGN CreateRoundRectRgn(
  int nLeftRect,      // x-coordinate of upper-left corner
  int nTopRect,       // y-coordinate of upper-left corner
  int nRightRect,     // x-coordinate of lower-right corner
  int nBottomRect,    // y-coordinate of lower-right corner
  int nWidthEllipse,  // height of ellipse
  int nHeightEllipse  // width of ellipse
);

Parameters

nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the region in logical units.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the region in logical units.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the region in logical units.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the region in logical units.
nWidthEllipse
[in] Specifies the width of the ellipse used to create the rounded corners in logical units.
nHeightEllipse
[in] Specifies the height of the ellipse used to create the rounded corners in logical units.

Return Values

If the function succeeds, the return value is the handle to the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, ExtCreateRegion, GetRegionData, DeleteObject, SelectObject


EqualRgn

The EqualRgn function checks the two specified regions to determine whether they are identical. The function considers two regions identical if they are equal in size and shape.

BOOL EqualRgn(
  HRGN hSrcRgn1,  // handle to first region
  HRGN hSrcRgn2   // handle to second region
);

Parameters

hSrcRgn1
[in] Handle to a region.
hSrcRgn2
[in] Handle to a region.

Return Values

If the two regions are equal, the return value is nonzero.

If the two regions are not equal, the return value is zero. A return value of ERROR means at least one of the region handles is invalid.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateRectRgn, CreateRectRgnIndirect


ExtCreateRegion

The ExtCreateRegion function creates a region from the specified region and transformation data.

HRGN ExtCreateRegion(
  CONST XFORM *lpXform,     // transformation data
  DWORD nCount,             // size of region data
  CONST RGNDATA *lpRgnData  // region data buffer
);

Parameters

lpXform
[in] Pointer to an XFORM structure that defines the transformation to be performed on the region. If this pointer is NULL, the identity transformation is used.
nCount
[in] Specifies the number of bytes pointed to by lpRgnData.
lpRgnData
[in] Pointer to a RGNDATA structure that contains the region data in logical units.

Return Values

If the function succeeds, the return value is the value of the region.

If the function fails, the return value is NULL.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

Region coordinates are represented as 27-bit signed integers.

An application can retrieve data for a region by calling the GetRegionData function.

Windows 95/98: Regions are no longer limited to the 64K heap.

Windows 95/98: World transforms that involve either shearing or rotations are not supported. ExtCreateRegion fails if the transformation matrix is anything other than a scaling or translation of the region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, GetRegionData, RGNDATA, XFORM


FillRgn

The FillRgn function fills a region by using the specified brush.

BOOL FillRgn(
  HDC hdc,    // handle to device context
  HRGN hrgn,  // handle to region to be filled
  HBRUSH hbr  // handle to brush used to fill the region
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region to be filled. The region's coordinates are presumed to be in logical units.
hbr
[in] Handle to the brush to be used to fill the region.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateBrushIndirect, CreateDIBPatternBrush, CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, PaintRgn


FrameRgn

The FrameRgn function draws a border around the specified region by using the specified brush.

BOOL FrameRgn(
  HDC hdc,     // handle to device context
  HRGN hrgn,   // handle to region to be framed
  HBRUSH hbr,  // handle to brush used to draw border
  int nWidth,  // width of region frame
  int nHeight  // height of region frame
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region to be enclosed in a border. The region's coordinates are presumed to be in logical units.
hbr
[in] Handle to the brush to be used to draw the border.
nWidth
[in] Specifies the width, in logical units, of vertical brush strokes.
nHeight
[in] Specifies the height, in logical units, of horizontal brush strokes.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, FillRgn, PaintRgn


GetPolyFillMode

The GetPolyFillMode function retrieves the current polygon fill mode.

int GetPolyFillMode(
  HDC hdc   // handle to device context
);

Parameters

hdc
[in] Handle to the device context.

Return Values

If the function succeeds, the return value specifies the polygon fill mode, which can be one of the following values.

Value | Meaning
ALTERNATE | Selects alternate mode (fills area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING | Selects winding mode (fills any region with a nonzero winding value).

If an error occurs, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, SetPolyFillMode


GetRegionData

The GetRegionData function fills the specified buffer with data describing a region. This data includes the dimensions of the rectangles that make up the region.

DWORD GetRegionData(
  HRGN hRgn,            // handle to region
  DWORD dwCount,        // size of region data buffer
  LPRGNDATA lpRgnData   // region data buffer
);

Parameters

hRgn
[in] Handle to the region.
dwCount
[in] Specifies the size, in bytes, of the lpRgnData buffer.
lpRgnData
[out] Pointer to a RGNDATA structure that receives the information. The dimensions of the region are in logical units. If this parameter is NULL, the return value contains the number of bytes needed for the region data.

Return Values

If the function succeeds and dwCount specifies an adequate number of bytes, the return value is always dwCount. If dwCount is too small or the function fails, the return value is 0. If lpRgnData is NULL, the return value is the required number of bytes.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The GetRegionData function is used in conjunction with the ExtCreateRegion function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreatePolygonRgn, CreatePolyPolygonRgn, CreateRectRgn, CreateRectRgnIndirect, CreateRoundRectRgn, ExtCreateRegion, RGNDATA


GetRgnBox

The GetRgnBox function retrieves the bounding rectangle of the specified region.

int GetRgnBox(
  HRGN hrgn,   // handle to a region
  LPRECT lprc  // bounding rectangle
);

Parameters

hrgn
[in] Handle to the region.
lprc
[out] Pointer to a RECT structure that receives the bounding rectangle in logical units.

Return Values

The return value specifies the region's complexity. It can be one of the following values:

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than a single rectangle.

If the hrgn parameter does not identify a valid region, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, RECT


InvertRgn

The InvertRgn function inverts the colors in the specified region.

BOOL InvertRgn(
  HDC hdc,    // handle to device context
  HRGN hrgn   // handle to region to be inverted
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region for which colors are inverted. The region's coordinates are presumed to be logical coordinates.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

On monochrome screens, the InvertRgn function makes white pixels black and black pixels white. On color screens, this inversion is dependent on the type of technology used to generate the colors for the screen.

For an example, see Using Brushes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, FillRgn, PaintRgn


OffsetRgn

The OffsetRgn function moves a region by the specified offsets.

int OffsetRgn(
  HRGN hrgn,     // handle to region
  int nXOffset,  // offset along x-axis
  int nYOffset   // offset along y-axis
);

Parameters

hrgn
[in] Handle to the region to be moved.
nXOffset
[in] Specifies the number of logical units to move left or right.
nYOffset
[in] Specifies the number of logical units to move up or down.

Return Values

The return value specifies the new region's complexity. It can be one of the following values.

Value | Meaning
NULLREGION | Region is empty.
SIMPLEREGION | Region is a single rectangle.
COMPLEXREGION | Region is more than one rectangle.
ERROR | An error occurred; region is unaffected.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions


PaintRgn

The PaintRgn function paints the specified region by using the brush currently selected into the device context.

BOOL PaintRgn(
  HDC hdc,    // handle to device context
  HRGN hrgn   // handle to region to be painted
);

Parameters

hdc
[in] Handle to the device context.
hrgn
[in] Handle to the region to be filled. The region's coordinates are presumed to be logical coordinates.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, FillRgn


PtInRegion

The PtInRegion function determines whether the specified point is inside the specified region.

BOOL PtInRegion(
  HRGN hrgn,  // handle to region
  int X,      // x-coordinate of point
  int Y       // y-coordinate of point
);

Parameters

hrgn
[in] Handle to the region to be examined.
X
[in] Specifies the x-coordinate of the point in logical units.
Y
[in] Specifies the y-coordinate of the point in logical units.

Return Values

If the specified point is in the region, the return value is nonzero.

If the specified point is not in the region, the return value is zero.

For an example, see Drawing Markers.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, RectInRegion


RectInRegion

The RectInRegion function determines whether any part of the specified rectangle is within the boundaries of a region.

BOOL RectInRegion(
  HRGN hrgn,         // handle to region
  CONST RECT *lprc   // pointer to rectangle
);

Parameters

hrgn
[in] Handle to the region.
lprc
[in] Pointer to a RECT structure containing the coordinates of the rectangle in logical units. The lower and right edges of the rectangle are not included.

Return Values

If any part of the specified rectangle lies within the boundaries of the region, the return value is nonzero.

If no part of the specified rectangle lies within the boundaries of the region, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, PtInRegion, RECT


SetPolyFillMode

The SetPolyFillMode function sets the polygon fill mode for functions that fill polygons.

int SetPolyFillMode(
  HDC hdc,            // handle to device context
  int iPolyFillMode   // polygon fill mode
);

Parameters

hdc
[in] Handle to the device context.
iPolyFillMode
[in] Specifies the new fill mode. This parameter can be one of the following values.
Value | Meaning
ALTERNATE | Selects alternate mode (fills the area between odd-numbered and even-numbered polygon sides on each scan line).
WINDING | Selects winding mode (fills any region with a nonzero winding value).

Return Values

The return value specifies the previous filling mode. If an error occurs, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

In general, the modes differ only in cases where a complex, overlapping polygon must be filled (for example, a five-sided polygon that forms a five-pointed star with a pentagon in the center). In such cases, ALTERNATE mode fills every other enclosed region within the polygon (that is, the points of the star), but WINDING mode fills all regions (that is, the points and the pentagon).

When the fill mode is ALTERNATE, GDI fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, GDI fills the area between the first and second side, between the third and fourth side, and so on.

When the fill mode is WINDING, GDI fills any region that has a nonzero winding value. This value is defined as the number of times a pen used to draw the polygon would go around the region. The direction of each edge of the polygon is important.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, GetPolyFillMode


SetRectRgn

The SetRectRgn function converts a region into a rectangular region with the specified coordinates.

BOOL SetRectRgn(
  HRGN hrgn,       // handle to region
  int nLeftRect,   // x-coordinate of upper-left corner of rectangle
  int nTopRect,    // y-coordinate of upper-left corner of rectangle
  int nRightRect,  // x-coordinate of lower-right corner of rectangle
  int nBottomRect  // y-coordinate of lower-right corner of rectangle
);

Parameters

hrgn
[in] Handle to the region.
nLeftRect
[in] Specifies the x-coordinate of the upper-left corner of the rectangular region in logical units.
nTopRect
[in] Specifies the y-coordinate of the upper-left corner of the rectangular region in logical units.
nRightRect
[in] Specifies the x-coordinate of the lower-right corner of the rectangular region in logical units.
nBottomRect
[in] Specifies the y-coordinate of the lower-right corner of the rectangular region in logical units.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Windows NT/2000: To get extended error information, call GetLastError.

Remarks

The region does not include the lower and right boundaries of the rectangle.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.
Library: Use Gdi32.lib.

See Also

Regions Overview, Region Functions, CreateRectRgn


Region Structures

The following structures are used with regions.

RGNDATA
RGNDATAHEADER


RGNDATA

The RGNDATA structure contains a header and an array of rectangles that compose a region. The rectangles are sorted top to bottom, left to right. They do not overlap.

typedef struct _RGNDATA {
    RGNDATAHEADER rdh;
    char          Buffer[1];
} RGNDATA, *PRGNDATA;

Members

rdh
Specifies a RGNDATAHEADER structure. The members of this structure specify the type of region (whether it is rectangular or trapezoidal), the number of rectangles that make up the region, the size of the buffer that contains the rectangle structures, and so on.
Buffer
Specifies an arbitrary-size buffer that contains the RECT structures that make up the region.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Regions Overview, Region Structures, RECT, RGNDATAHEADER


RGNDATAHEADER

The RGNDATAHEADER structure describes the data returned by the GetRegionData function.

typedef struct _RGNDATAHEADER {
    DWORD dwSize;
    DWORD iType;
    DWORD nCount;
    DWORD nRgnSize;
    RECT  rcBound;
} RGNDATAHEADER, *PRGNDATAHEADER;

Members

dwSize
Specifies the size, in bytes, of the header.
iType
Specifies the type of region. This value must be RDH_RECTANGLES.
nCount
Specifies the number of rectangles that make up the region.
nRgnSize
Specifies the size of the buffer required to receive the RECT structure that specifies the coordinates of the rectangles that make up the region. If the size is not known, this member can be zero.
rcBound
Specifies a bounding rectangle for the region in logical units.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wingdi.h; include Windows.h.

See Also

Regions Overview, Region Structures, GetRegionData, RECT, RGNDATA


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.