在做项目时,需要打印窗体上指定某部分的内容,现将代码分享如下。
首先要知道API
//调入外部的非托管代码,使用从gdi32.dll库导入的函数BitBlt,使用Windows GDI。
[DllImport(“gdi32.dll”)]
Public static extern long BitBlt(IntPtr hdcDest,int nXDest,int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,int nXSrc,int nYSrc,int dwRop);
解释:
hdcDest 目标设备的句柄
nXDest 目标对象的左上角的X坐标
nYDest 目标对象的左上角的Y坐标
nWidth 目标对象的矩形宽度
nHeight 目标对象的矩形高度
hdcSrc 源设备的句柄
nXSrc 源对象的左上角的X坐标
nYSrc 源对象的左上角的Y坐标
dwRop 光栅的操作值
详细说明可以参照MSDN
//抓取要打印的内容,并存为图片,我用的是一个图表控件,名称为chartImage
Private Bitmap memoryImage;
Private void CaptureScreen()
{
Graphics myGraphics=chartImage.CreateGraphics();
memoryImage=new Bitmap(chartImage.ClientRectangle.Width, chartImage.ClientRectangle.Height,myGraphics);
Graphics memoryGraphics=Graphics.FromImage(memoryImage);
IntPtr dc1=myGraphics.GetHdc();
IntPtr dc2=memoryGraphics.GetHdc();
BitBlt(dc2,0,0, chartImage.ClientRectangle.Width, chartImage.ClientRectangle.Height,dc1, chartImage.ClientRectangle.Top, chartImage.ClientRectangle.Left,13369376);
myGraphics.ReleaseHdc(dc1);
memoryGraphics.ReleaseHdc(dc2);
}
//打印文档
Private void printDocument1_PrintPage(object sender,System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage,0,0);
}
//打印
Private void Button1_click(object sender,EventArgs e)
{
If(printDialog1.ShowDialog()==DialogResult.OK)
{
printDocument1.PrinterSettings=printDialog1.PrinterSettings;
printPreviewDialog1.Document=printDocument1;
printPreviewDialog1.ShowDialog();
}
}
OK , That’s all !