Using the Print Property Sheet

[This is preliminary documentation and subject to change.]

This topic describes sample code that displays a Print property sheet so a user can select options for printing a document. The sample code first allocates and initializes a PRINTDLGEX structure, then calls the PrintDlgEx function to display the property sheet.

The sample code sets the PD_RETURNDC flag in the Flags member of the PRINTDLG structure. This causes the PrintDlgEx function to return a device context handle for the selected printer in the hDC member. You can use the handle in functions such as DrawText that render output sent to the printer.

On input, the sample code sets the hDevMode and hDevNames members to NULL. If the function returns S_OK, these members return handles to DEVMODE and DEVNAMES structures containing the user's input and information about the printer. You can use this information to prepare the output to be sent to the selected printer.

After the printing operation has been completed, the sample code frees the DEVMODE and DEVNAMES buffers and calls the DeleteDC function to delete the device context.

HRESULT DisplayPrintPropertySheet(
    HWND hWnd  // Window that owns the property sheet
)
{
HRESULT hResult;
LPPRINTDLGEX pPDX = NULL;
LPPRINTPAGERANGE pPageRanges = NULL;

// Allocate the PRINTDLGEX structure.

pPDX = (LPPRINTDLGEX)GlobalAlloc(GPTR, sizeof(PRINTDLGEX));
if (!pPDX)
    return E_OUTOFMEMORY;

// Allocate an array of PRINTPAGERANGE structures.

pPageRanges = (LPPRINTPAGERANGE) GlobalAlloc(GPTR, 
                   10 * sizeof(PRINTPAGERANGE));
if (!pPageRanges)
    return E_OUTOFMEMORY;

//  Initialize the PRINTDLGEX structure.

pPDX->lStructSize = sizeof(PRINTDLGEX);
pPDX->hwndOwner = hWnd;
pPDX->hDevMode = NULL;
pPDX->hDevNames = NULL;
pPDX->hDC = NULL;
pPDX->Flags = PD_RETURNDC | PD_COLLATE;
pPDX->Flags2 = 0;
pPDX->ExclusionFlags = 0;
pPDX->nPageRanges = 0;
pPDX->nMaxPageRanges = 10;
pPDX->lpPageRanges = pPageRanges;
pPDX->nMinPage = 1;
pPDX->nMaxPage = 1000;
pPDX->nCopies = 1;
pPDX->hInstance = 0;
pPDX->lpPrintTemplateName = NULL;
pPDX->lpCallback = NULL;
pPDX->nPropertyPages = 0;
pPDX->lphPropertyPages = NULL;
pPDX->nStartPage = START_PAGE_GENERAL;
pPDX->dwResultAction = 0;

//  Invoke the Print property sheet.

hResult = PrintDlgEx(pPDX);

if ( (hResult == S_OK) &&
           pPDX->dwResultAction == PD_RESULT_PRINT) {

    // User clicked the Print button, so
    // use the DC and other information returned in the 
    // PRINTDLGEX structure to print the document

}

if (pPDX->hDC != NULL) 
    DeleteDC(pPDX->hDC);
if (pPDX->hDevMode != NULL) 
    GlobalFree(pPDX->hDevMode); 
if (pPDX->hDevNames != NULL) 
    GlobalFree(pPDX->hDevNames); 

return hResult;
}