12.8.5 Adding a GetPrinterDC Function

To create a printer device context for your application, you must add a function to your C-language source file. The GetPrinterDC function uses the PrintDlg function to use the Print common dialog box and then creates a printer device context by using the driver name, device name, and printer port given in the PRINTDLG structure. To create this function, add the following statements to the C-language source file:

HDC GetPrinterDC()
{
    HDC         hDC;
    LPDEVMODE   lpDevMode = NULL;
    LPDEVNAMES  lpDevNames;
    LPSTR       lpszDriverName;
    LPSTR       lpszDeviceName;
    LPSTR       lpszPortName;

    if (!PrintDlg((LPPRINTDLG) &pd))
        return (NULL);

    if (pd.hDC) {
        hDC = pd.hDC;
    }

    else {
        if (!pd.hDevNames)
            return (NULL);

        lpDevNames = (LPDEVNAMES) GlobalLock(pd.hDevNames);
        lpszDriverName =
            (LPSTR) lpDevNames + lpDevNames->wDriverOffset;
        lpszDeviceName =
            (LPSTR) lpDevNames + lpDevNames->wDeviceOffset;
        lpszPortName   =
            (LPSTR) lpDevNames + lpDevNames->wOutputOffset;
        GlobalUnlock(pd.hDevNames);

        if (pd.hDevMode)
            lpDevMode = (LPDEVMODE) GlobalLock(pd.hDevMode);

        hDC = CreateDC(lpszDriverName, lpszDeviceName,
            lpszPortName, (LPSTR) lpDevMode);

        if (pd.hDevMode && lpDevMode)
            GlobalUnlock(pd.hDevMode);
      }

    if (pd.hDevNames)
        GlobalFree(pd.hDevNames);
    if (pd.hDevMode)
        GlobalFree(pd.hDevMode);
    return(hDC);
}