透過 Printer()->Handle 取得印表機 DC,呼叫 GetDeviceCaps 查詢各項能力值。
int dpiX = GetDeviceCaps(Printer->Handle, LOGPIXELSX); // 水平 DPI
int dpiY = GetDeviceCaps(Printer->Handle, LOGPIXELSY); // 垂直 DPI
VCL TPrinter 屬性直接提供:
int printableWidth = Printer->PageWidth; // 可列印寬度 (像素)
int printableHeight = Printer->PageHeight; // 可列印高度 (像素)
int physicalWidth = GetDeviceCaps(Printer->Handle, PHYSICALWIDTH);
int physicalHeight = GetDeviceCaps(Printer->Handle, PHYSICALHEIGHT);
注意:實體尺寸 ≥ 可列印區域,差值為不可列印邊距 (硬體限制)。
double widthInch = (double)physicalWidth / dpiX;
double heightInch = (double)physicalHeight / dpiY;
double widthCm = widthInch * 2.54;
double heightCm = heightInch * 2.54;
| 索引常數 | 意義 | 用途 |
|---|---|---|
| HORZSIZE / VERTSIZE | 螢幕/紙張實體尺寸 (毫米) | 螢幕為實際可視區,印表機為紙張大小 |
| HORZRES / VERTRES | 可繪製區域解析度 (像素) | 印表機同 PageWidth/PageHeight |
| BITSPIXEL | 色深 (位元/像素) | 1=單色, 4=16色, 8=256色, 24=真彩色 |
| PLANES | 色彩平面數 | 通常為 1 |
| NUMBRUSHES / NUMPENS / NUMFONTS | 可用筆刷/畫筆/字型數 | 裝置能力查詢 |
void __fastcall TForm1::BtnGetPrinterInfoClick(TObject *Sender) {
if (!Printer->Printers->Count) {
ShowMessage("系統無印表機");
return;
}
Printer->PrinterIndex = 0; // 選擇預設印表機
Printer->BeginDoc(); // 必須 BeginDoc 後 Handle 才有效
HDC hdc = Printer->Handle;
int dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
int dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
int physW = GetDeviceCaps(hdc, PHYSICALWIDTH);
int physH = GetDeviceCaps(hdc, PHYSICALHEIGHT);
int printW = Printer->PageWidth;
int printH = Printer->PageHeight;
AnsiString info = "印表機參數報表:\n\n";
info += "解析度: " + IntToStr(dpiX) + " x " + IntToStr(dpiY) + " DPI\n";
info += "實體紙張: " + IntToStr(physW) + " x " + IntToStr(physH) + " 像素\n";
info += "可列印區: " + IntToStr(printW) + " x " + IntToStr(printH) + " 像素\n";
info += "實體尺寸: " + FormatFloat("0.00", (double)physW/dpiX) + " x " +
FormatFloat("0.00", (double)physH/dpiY) + " 英吋\n";
info += "邊距 (像素): 左/右=" + IntToStr((physW-printW)/2) +
" 上/下=" + IntToStr((physH-printH)/2);
Printer->Abort(); // 不實際列印,僅查詢
ShowMessage(info);
}
BeginDoc 後、EndDoc/Abort 前使用Printer->PrinterIndex 切換後需重新 BeginDoc