How can I get a printers device context?

c++, printing, windows

Solution

The easiest way is to use construct the device context from `PRINTDLG.hDevMode` and `PRINTDLG.hDevNames` after calling `PrintDlg` if using win32 API, or calling `CPrintDialog::GetPrinterDC` if you're using MFC.

If using MFC:

CPrintDialog dlgPrint(FALSE, PD_USEDEVMODECOPIES);
HDC hPrinterDC = dlgPrint.GetPrinterDC();

or win32 API:

HDC hPrinterDC = NULL;
PRINTDLG dlgPrint;
if (PrintDlg(&dlgPrint) && dlgPrint.hDevMode != NULL)
{
    DEVNAMES *pDevNames = (DEVNAMES*)GlobalLock(dlgPrint.hDevNames);
    DEVMODE* pDevMode = NULL;
    if (dlgPrint.hDevMode != NULL)
        pDevMode = GlobalLock(dlgPrint.hDevMode);
    hPrinterDC = CreateDC((LPCTSTR)pDevNames + pDevNames->wDriverOffset,
                          (LPCTSTR)pDevNames + pDevNames->wDeviceOffset,
                          (LPCTSTR)pDevNames + pDevNames->wOutputOffset,
                          pDevMode);
    GlobalUnlock(dlgPrint.hDevNames);
    if (dlgPrint.hDevMode != NULL)
        GlobalUnlock(dlgPrint.hDevMode);
}

Problem

I'm on Windows and trying to print an Enhanced Metafile (EMF) using PlayEnhMetaFile(). I'm currently displaying it using a device context for a window on the screen, but now I want to send it to a printer. How can I get a device context for the printer and pass it into this function properly?

Original source