打印某个控件或者窗体的某部分

本文介绍如何在项目中实现打印窗体上特定控件的内容,如图表控件。通过调用gdi32.dll的BitBlt API函数,抓取控件的图像并进行打印,详细代码包括CaptureScreen、PrintPage和Button点击事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做项目时,需要打印窗体上指定某部分的内容,现将代码分享如下。

首先要知道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 !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值