实现C#打印窗体实例详解

来源:互联网 发布:python 改变图片颜色 编辑:程序博客网 时间:2024/05/01 14:41

如何在 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#打印窗体有所帮助。


转自:http://developer.51cto.com/art/200908/146909.htm

原创粉丝点击