代码功能介绍(以备以后查询):该代码片段展示了如何将TPanel
控件的内容作为图像打印出来。首先,代码创建了一个与TPanel
大小相同的位图,并通过BitBlt
函数将TPanel
的内容复制到位图中。接着,代码配置打印机,设置自定义纸张大小,并将位图绘制到打印机画布上。最后,代码完成打印任务并释放相关资源。整个过程涉及Windows API和VCL库的使用,确保图像能够准确打印。
//库文件引入
#include <Windows.hpp>
#include <vcl.h>
#pragma hdrstop
#include <IniFiles.hpp>
#include <System.Types.hpp>
#include <System.Classes.hpp> // TShiftState
#include <Vcl.Controls.hpp> // 控件基类
#include <vcl.printers.hpp>
#include <winspool.h> // 打印机API头文件
//-------------实现了,将panel容器,以图片全体打印出来,因为使用尺寸对正非常麻烦
TBitmap *bitmap = new TBitmap();
try
{
// 设置位图的大小与TPanel相同
bitmap->Width = Panel1->Width;
bitmap->Height = Panel1->Height;
// 创建一个兼容的DC并与位图关联
HDC hdcPanel = GetDC(Panel1->Handle);
HDC hdcBitmap = CreateCompatibleDC(hdcPanel);
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcBitmap, bitmap->Handle);
// 位图填充透明背景
BitBlt(hdcBitmap, 0, 0, bitmap->Width, bitmap->Height, hdcPanel, 0, 0, SRCCOPY);
// 恢复旧的位图
SelectObject(hdcBitmap, hbmOld);
DeleteDC(hdcBitmap);
ReleaseDC(Panel1->Handle, hdcPanel);
// 打印位图
TPrinter *printer = Printer();
printer->PrinterIndex = -1; // 选择默认打印机
//Printer()->PrinterIndex = Printer()->Printers->IndexOf(L"打印机名称"); // 指定打印机
//Printer()->PaperSize = DMPAPER_USER; // 设置为用户自定义纸张
String ADevice, ADriver, APort;
THandle DeviceMode;
PDEVMODE DevMode;
int length =imgBackground->Height ; // 设定自定义纸张的高度
int wid =imgBackground->Width; // 设定自定义纸张的宽度
// 获取当前打印机的信息
Printer()->GetPrinter(ADevice, ADriver, APort, DeviceMode);
// 锁定DEVMODE结构以进行修改
DevMode = (PDEVMODE)GlobalLock((HGLOBAL)DeviceMode);
// 设置自定义纸张大小
DevMode->dmPaperSize = DMPAPER_USER; // 设置为自定义纸张
DevMode->dmFields |= DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH; // 允许重新设置纸张大小、宽度和长度
DevMode->dmPaperWidth = wid; // 设置纸张宽度
DevMode->dmPaperLength = length; // 设置纸张长度
// 解锁DEVMODE结构
GlobalUnlock((HGLOBAL)DeviceMode);
Printer()->Orientation = poLandscape;
printer->BeginDoc();
try
{
printer->Canvas->StretchDraw(Rect(0, 0, printer->PageWidth, printer->PageHeight), bitmap);
}
__finally
{
printer->EndDoc();
delete printer;
}
}
__finally
{
delete bitmap;
}