Printing in Win32

I have this program that should print a rectangle on a printer. It uses standard Win32 API calls.

HANDLE hdl;
DEVMODE* devmode;
OpenPrinter(L"HP Deskjet F4400 series", &hdl, NULL);
int size = DocumentProperties(NULL, hdl, L"HP Deskjet F4400 series", NULL, NULL, 0);
devmode = (DEVMODE*)malloc(size);
DocumentProperties(NULL, hdl, L"HP Deskjet F4400 series", devmode, NULL, DM_OUT_BUFFER);
HDC printerDC = CreateDC(L"WINSPOOL", devmode->dmDeviceName, NULL, devmode);
DOCINFO info;
memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
StartDoc(printerDC, &info);
StartPage(printerDC);
Rectangle(printerDC, 100, 100, 200, 200);
EndPage(printerDC);
EndDoc(printerDC);
DeleteDC(printerDC);

All API calls succeed, but printing fails. What have I done wrong?

+3
source share
1 answer

There are several issues here:

  • You do not close the printer with ClosePrinter
  • Parameters OpenPrinterand CreateDCwrong - they should be the actual name of the printer, not the printer class. (When I tried your code, the APIs failed.)

I set up a GDI print sample to print to the default printer, and it works; I changed your sample correctly:

HANDLE hdl;
DEVMODE* devmode;
wchar_t szPrinter[MAX_PATH];
DWORD cchPrinter(ARRAYSIZE(szPrinter));
GetDefaultPrinter(szPrinter, &cchPrinter);
OpenPrinter(szPrinter, &hdl, NULL);
int size = DocumentProperties(NULL, hdl, szPrinter, NULL, NULL, 0);
devmode = (DEVMODE*)malloc(size);
DocumentProperties(NULL, hdl, szPrinter, devmode, NULL, DM_OUT_BUFFER);
HDC printerDC = CreateDC(L"WINSPOOL", szPrinter, NULL, devmode);
DOCINFO info;
memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
StartDoc(printerDC, &info);
StartPage(printerDC);
Rectangle(printerDC, 100, 100, 200, 200);
EndPage(printerDC);
EndDoc(printerDC);
DeleteDC(printerDC);
ClosePrinter(hdl);
+2
source

All Articles