您的位置:首页 > 编程语言 > C#

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

2012-05-21 14:50 686 查看
如何在 Windows 下实现C#打印窗体作为C#开发过程的一部分,通常会希望C#打印窗体的副本。下面的代码示例演示如何使用 CopyFromScreen 方法来实现C#打印窗体的副本。
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;

public class Form1 :
Form
{//实现C#打印窗体
private Button printButton = new Button();
private PrintDocument printDocument1 = new PrintDocument();

public Form1()
{
printButton.Text = "Print Form";
printButton.Click += new EventHandler(printButton_Click);
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
this.Controls.Add(printButton);
}

void printButton_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocument1.Print();
}
//实现C#打印窗体
Bitmap memoryImage;

private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(
this.Location.X, this.Location.Y, 0, 0, s);
}

private void printDocument1_PrintPage(System.Object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}

//实现C#打印窗体

public static void Main()
{
Application.Run(new Form1());
}
}


◆C#打印窗体之编译代码

这是一个完整的代码示例,其中包含 Main 方法。

◆C#打印窗体之可靠编程

1、以下情况可能会导致异常:

2、您没有访问该打印机的权限。

3、没有安装打印机。

◆C#打印窗体之安全

为了运行此代码示例,您必须能够访问与计算机一起使用的打印机。

C#打印窗体的具体内容就向你介绍到这里,希望对你了解和学习C#打印窗体有所帮助。

转自:http://developer.51cto.com/art/200908/146909.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: