显示“打印”对话框
获取打印机的设备上下文句柄的一种方法是显示打印对话框,并允许用户选择打印机。 PrintDlg 函数 (显示对话框) 具有一个参数,即 PRINTDLG 结构的地址。 PRINTDLG 结构具有多个成员,但你可以将其中的大多数设置为默认值。 需要设置的两个成员是 lStructSize 和 Flags。 将 lStructSize 设置为 PRINTDLG 变量的大小,并将 Flags 设置为 PD_RETURNDC。 将 Flags 设置为 PC_RETURNDC 指定希望 PrintDlg 函数使用用户选择的打印机的设备上下文句柄填充 hDC 字段。
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;
INT main()
{
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
DOCINFO docInfo;
ZeroMemory(&docInfo, sizeof(docInfo));
docInfo.cbSize = sizeof(docInfo);
docInfo.lpszDocName = "GdiplusPrint";
// Create a PRINTDLG structure, and initialize the appropriate fields.
PRINTDLG printDlg;
ZeroMemory(&printDlg, sizeof(printDlg));
printDlg.lStructSize = sizeof(printDlg);
printDlg.Flags = PD_RETURNDC;
// Display a print dialog box.
if(!PrintDlg(&printDlg))
{
printf("Failure\n");
}
else
{
// Now that PrintDlg has returned, a device context handle
// for the chosen printer is in printDlg->hDC.
StartDoc(printDlg.hDC, &docInfo);
StartPage(printDlg.hDC);
Graphics* graphics = new Graphics(printDlg.hDC);
Pen* pen = new Pen(Color(255, 0, 0, 0));
graphics->DrawRectangle(pen, 200, 500, 200, 150);
graphics->DrawEllipse(pen, 200, 500, 200, 150);
graphics->DrawLine(pen, 200, 500, 400, 650);
delete pen;
delete graphics;
EndPage(printDlg.hDC);
EndDoc(printDlg.hDC);
}
if(printDlg.hDevMode)
GlobalFree(printDlg.hDevMode);
if(printDlg.hDevNames)
GlobalFree(printDlg.hDevNames);
if(printDlg.hDC)
DeleteDC(printDlg.hDC);
GdiplusShutdown(gdiplusToken);
return 0;
}