C# winform 打印当前窗体
时间: 2023-07-30 10:07:14 浏览: 83
要打印当前窗体,可以使用C#的PrintDocument类和PrintPreviewDialog类来实现。以下是实现的步骤:
1. 创建一个PrintDocument类的实例,并设置它的PrintPage事件处理程序。
```csharp
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
```
2. 在PrintPage事件处理程序中,使用Graphics类的DrawImage方法将当前窗体的内容绘制到打印页面上。
```csharp
private void PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bitmap = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bitmap, new Rectangle(0, 0, this.Width, this.Height));
e.Graphics.DrawImage(bitmap, e.MarginBounds);
}
```
3. 创建一个PrintPreviewDialog类的实例,并将前面创建的PrintDocument类实例赋给它的Document属性。
```csharp
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
printPreviewDialog.Document = printDocument;
```
4. 调用PrintPreviewDialog类的ShowDialog方法来显示打印预览对话框。
```csharp
printPreviewDialog.ShowDialog();
```
完整的代码示例:
```csharp
private void buttonPrint_Click(object sender, EventArgs e)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += new PrintPageEventHandler(PrintPage);
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
printPreviewDialog.Document = printDocument;
printPreviewDialog.ShowDialog();
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bitmap = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bitmap, new Rectangle(0, 0, this.Width, this.Height));
e.Graphics.DrawImage(bitmap, e.MarginBounds);
}
```
阅读全文