http://blog.csdn.net/weican57/article/details/6615442

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

代码如下:

[csharp] view plaincopy
  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.         }  


 

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


本文转载:CSDN博客