在C#中实现打印功能(C#中PrintDialog,PrintDocument的使用) (转)
时间: 2024-03-12 15:46:59 浏览: 91
C#打印功能(PrintDialog,PrintDocument).rar_C#打印_PrintDialog_c# printD
5星 · 资源好评率100%
在C#中实现打印功能的步骤如下:
1. 引入命名空间
```csharp
using System.Drawing.Printing;
using System.Windows.Forms;
```
2. 创建打印对话框
```csharp
PrintDialog printDialog = new PrintDialog();
```
3. 显示打印对话框
```csharp
if (printDialog.ShowDialog() == DialogResult.OK)
{
// 用户点击了“打印”按钮
}
```
4. 创建打印文档对象
```csharp
PrintDocument printDocument = new PrintDocument();
```
5. 设置打印文档的打印机
```csharp
printDocument.PrinterSettings = printDialog.PrinterSettings;
```
6. 设置打印文档的打印事件
```csharp
printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
```
7. 实现打印事件
```csharp
private void PrintPage(object sender, PrintPageEventArgs e)
{
// 在此处编写打印逻辑
}
```
8. 开始打印
```csharp
printDocument.Print();
```
完整的代码示例:
```csharp
using System.Drawing.Printing;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrinterSettings = printDialog.PrinterSettings;
printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
printDocument.Print();
}
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Hello, World!", new Font("Arial", 12), Brushes.Black, new PointF(0, 0));
}
}
```
阅读全文