代码:https://download.csdn.net/download/kaileychina/88666094
在WPF (Windows Presentation Foundation) 中,打印功能可以通过使用PrintDialog
类来实现。以下是一个简单的示例,展示了如何在WPF应用程序中添加打印功能。
首先,你需要创建一个WPF项目。如果你还没有这样做,请在Visual Studio中创建一个新的WPF应用程序项目。
以下是添加打印功能的步骤:
- 打开你的WPF项目,并在XAML中添加一个按钮来触发打印操作。例如,你可以在
MainWindow.xaml
中添加以下代码:
xml复制代码
<Window x:Class="WpfPrintDemo.MainWindow" | |
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | |
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | |
Title="MainWindow" Height="350" Width="525"> | |
<Grid> | |
<Button Content="Print" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="25" Margin="10" Click="Print_Click"/> | |
</Grid> | |
</Window> |
- 在代码文件(例如
MainWindow.xaml.cs
)中添加打印逻辑。在Print_Click
方法中,你可以创建一个PrintDialog
实例,并设置其属性以定制打印输出。以下是一个基本的打印逻辑示例:
csharp复制代码
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Printing; | |
namespace WpfPrintDemo | |
{ | |
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
} | |
private void Print_Click(object sender, RoutedEventArgs e) | |
{ | |
// 创建一个 PrintDocument 对象并设置其属性 | |
PrintDocument printDocument = new PrintDocument(); | |
printDocument.PrintPage += (sender1, e1) => | |
{ | |
// 在此处绘制要打印的内容。例如,你可以绘制一个简单的文本字符串。 | |
e1.Graphics.DrawString("Hello, World!", new Font("Arial", 16), Brushes.Black, new PointF(10, 10)); | |
}; | |
// 显示打印对话框并执行打印操作 | |
printDocument.ShowPrintDialog(); | |
} | |
} | |
} |
这个例子中,我们创建了一个PrintDocument
对象,并为其PrintPage
事件添加了一个事件处理程序。在事件处理程序中,我们使用e1.Graphics
对象来绘制要打印的文本。最后,我们通过调用ShowPrintDialog()
方法显示打印对话框,用户可以在其中选择打印机和其他打印选项。
请注意,这是一个非常基础的示例。在实际应用程序中,你可能需要绘制更复杂的布局,或者将数据绑定到打印输出。此外,你可能还需要处理纸张大小、边距等其他打印相关的设置。这些都可以通过设置PrintDocument
的属性或修改事件处理程序中的代码来实现。