我有这个程序应该在打印机上打印一个矩形。它使用标准的Win32 API调用。
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);
所有API调用都成功,但不会发生打印。我做错了什么?
答案 0 :(得分:2)
这里有几个问题:
ClosePrinter
OpenPrinter
和CreateDC
的参数不正确 - 它们必须是实际的打印机名称,而不是打印机类。 (当我尝试使用您的代码时,API失败了。)我调整了GDI打印样本以打印到默认打印机,它可以工作;我适当地修改了你的样本:
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);