4.4.2 Displaying a Print Dialog Box for the Default Printer

To display a Print dialog box for the default printer, an application must initialize a PRINTDLG structure and then call the PrintDlg function.

The members of the PRINTDLG structure can contain information about such items as the following:

The printer device context

Values that should appear in the dialog box controls

The hook function and custom dialog box template to use for a customized version of the Print dialog box or Print Setup dialog box

An application can display a Print dialog box for the currently installed printer by performing the following steps:

1.Setting the PD_RETURNDC flag in the Flags member of the PRINTDLG structure. (This flag should only be set if the application requires a device-context handle.)

2.Initializing the lStructSize, hDevMode, and hDevNames members.

3.Calling the PrintDlg function and passing a pointer to the PRINTDLG structure just initialized.

Setting the PD_RETURNDC flag causes PrintDlg to display the Print dialog box and return a handle identifying a printer device context in the hDC member of the PRINTDLG structure. (The application passes the device-context handle as the first parameter to the GDI functions that render output on the printer.)

The following example initializes the members of the PRINTDLG structure and calls the PrintDlg function prior to printing output. This structure should be global or declared as a static variable.

PRINTDLG pd;

/* Set all structure members to zero. */

memset(&pd, 0, sizeof(PRINTDLG));

/* Initialize the necessary PRINTDLG structure members. */

pd.lStructSize = sizeof(PRINTDLG);
pd.hwndOwner = hwnd;
pd.Flags = PD_RETURNDC;

/* Print a test page if successful. */

if (PrintDlg(&pd) != 0) {
    Escape(pd.hDC, STARTDOC, 8, "Test-Doc", NULL);

    /* Print text and rectangle. */

    TextOut(pd.hDC, 50, 50, "Common Dialog Test Page", 23);
    Rectangle(pd.hDC, 50, 90, 625, 105);
    Escape(pd.hDC, NEWFRAME, 0, NULL, NULL);
    Escape(pd.hDC, ENDDOC, 0, NULL, NULL);
    DeleteDC(pd.hDC);
    if (pd.hDevMode != NULL)
       GlobalFree(pd.hDevMode);
    if (pd.hDevNames != NULL)
       GlobalFree(pd.hDevNames);
}
else
    ErrorHandler();