實現C#打印窗體實例詳解

如何在 Windows 下實現C#打印窗體作爲C#開發過程的一部分,通常會希望C#打印窗體的副本。下面的代碼示例演示如何使用 CopyFromScreen 方法來實現C#打印窗體的副本。

  1. using System;  
  2. using System.Windows.Forms;  
  3. using System.Drawing;  
  4. using System.Drawing.Printing;  
  5.  
  6. public class Form1 :  
  7.  Form  
  8. {//實現C#打印窗體  
  9. private Button printButton = new Button();  
  10. private PrintDocument printDocument1 = new PrintDocument();  
  11.  
  12. public Form1()  
  13.  {  
  14.  printButton.Text = "Print Form";  
  15.  printButton.Click += new EventHandler(printButton_Click);  
  16.  printDocument1.PrintPage +=   
  17. new PrintPageEventHandler(printDocument1_PrintPage);  
  18. this.Controls.Add(printButton);  
  19.  }  
  20.  
  21. void printButton_Click(object sender, EventArgs e)  
  22.  {  
  23.  CaptureScreen();  
  24.  printDocument1.Print();  
  25.  }  
  26. //實現C#打印窗體  
  27.  Bitmap memoryImage;  
  28.  
  29. private void CaptureScreen()  
  30.  {  
  31.  Graphics myGraphics = this.CreateGraphics();  
  32.  Size s = this.Size;  
  33.  memoryImage = new Bitmap(s.Width, s.Height, myGraphics);  
  34.  Graphics memoryGraphics = Graphics.FromImage(memoryImage);  
  35.  memoryGraphics.CopyFromScreen(  
  36. this.Location.X, this.Location.Y, 0, 0, s);  
  37.  }  
  38.  
  39. private void printDocument1_PrintPage(System.Object sender,     
  40. System.Drawing.Printing.PrintPageEventArgs e)  
  41.  {  
  42.  e.Graphics.DrawImage(memoryImage, 0, 0);  
  43.  }  
  44.  
  45.    //實現C#打印窗體  
  46.  
  47. public static void Main()  
  48.  {  
  49.  Application.Run(new Form1());  
  50.  }  
  51. }  

◆C#打印窗體之編譯代碼

這是一個完整的代碼示例,其中包含 Main 方法。

◆C#打印窗體之可靠編程

1、以下情況可能會導致異常:

2、您沒有訪問該打印機的權限。

3、沒有安裝打印機。

◆C#打印窗體之安全

爲了運行此代碼示例,您必須能夠訪問與計算機一起使用的打印機。

C#打印窗體的具體內容就向你介紹到這裏,希望對你瞭解和學習C#打印窗體有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章