實(shí)現(xiàn)C#打印窗體實(shí)例詳解
如何在 Windows 下實(shí)現(xiàn)C#打印窗體作為C#開發(fā)過程的一部分,通常會(huì)希望C#打印窗體的副本。下面的代碼示例演示如何使用 CopyFromScreen 方法來實(shí)現(xiàn)C#打印窗體的副本。
- using System;
- using System.Windows.Forms;
- using System.Drawing;
- using System.Drawing.Printing;
- public class Form1 :
- Form
- {//實(shí)現(xiàn)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();
- }
- //實(shí)現(xiàn)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);
- }
- //實(shí)現(xiàn)C#打印窗體
- public static void Main()
- {
- Application.Run(new Form1());
- }
- }
◆C#打印窗體之編譯代碼
這是一個(gè)完整的代碼示例,其中包含 Main 方法。
◆C#打印窗體之可靠編程
1、以下情況可能會(huì)導(dǎo)致異常:
2、您沒有訪問該打印機(jī)的權(quán)限。
3、沒有安裝打印機(jī)。
◆C#打印窗體之安全
為了運(yùn)行此代碼示例,您必須能夠訪問與計(jì)算機(jī)一起使用的打印機(jī)。
C#打印窗體的具體內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#打印窗體有所幫助。
【編輯推薦】