【.Net码农】C# WinForm 打印

本文介绍如何使用 C# 实现打印功能,包括打印、打印预览和打印设置等操作,并提供了完整的代码示例。

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

http://blog.youkuaiyun.com/weican57/article/details/6615442

在工具箱中的打印工具中拖printDialog、printDocument、printPreviewDialog、pageSetupDialog到页面中。页面中拖三个按钮,分别是“打印”、“打印设置”、“打印预览”。

代码如下:

[csharp]  view plain copy
  1. //打印  
  2.   
  3.         private void btnPrint_Click(object sender, EventArgs e)  
  4.   
  5.         {  
  6.   
  7.             if (this.printDialog1.ShowDialog() == DialogResult.OK)  
  8.   
  9.                 CaptureScreen();  
  10.   
  11.                 this.printDocument1.Print();   
  12.   
  13.         }  
  14.   
  15.    
  16.   
  17.         //打印预览  
  18.   
  19.         private void btnView_Click(object sender, EventArgs e)  
  20.   
  21.         {  
  22.   
  23.             CaptureScreen();  
  24.   
  25.             this.printPreviewDialog1.ShowDialog();  
  26.   
  27.    
  28.   
  29.         }  
  30.   
  31.         //打印设置  
  32.   
  33.         private void btnSet_Click(object sender, EventArgs e)  
  34.   
  35.         {  
  36.   
  37.             this.pageSetupDialog1.ShowDialog();   
  38.   
  39.         }  
  40.   
  41.    
  42.   
  43.          //如果要打印整个窗体  
  44.   
  45.         [System.Runtime.InteropServices.DllImport( "gdi32.dll ")]  
  46.   
  47.         public static extern long BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);  
  48.   
  49.    
  50.   
  51.         private void CaptureScreen()   
  52.   
  53.         {   
  54.   
  55.             Graphics mygraphics = this.panel1 .CreateGraphics ();   
  56.   
  57.             Size s = this.panel1 .Size; //如果要打印整个窗体Size s = this. Size;  
  58.   
  59.             memoryImage = new Bitmap(s.Width, s.Height, mygraphics);   
  60.   
  61.             Graphics memoryGraphics = Graphics.FromImage(memoryImage);   
  62.   
  63.             IntPtr dc1 = mygraphics.GetHdc();   
  64.   
  65.             IntPtr dc2 = memoryGraphics.GetHdc();   
  66.   
  67.             BitBlt(dc2, 0, 0, this.Width, this.Height, dc1, 0, 0, 13369376);   
  68.   
  69.             mygraphics.ReleaseHdc(dc1);   
  70.   
  71.             memoryGraphics.ReleaseHdc(dc2);  
  72.   
  73.         }  


 

  这种方式的打印相当于页面的截屏效果,如果打印时弹出的选择打印机及相关设置的页面在点击“打印”时未能及时关闭就会被抓到打印页面中,所以为了避免这种情况,就把点击“打印”后的设置页面拖动到需打印的页面之外即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值