请求帮助:用C#实现文档打印时显示提示消息
在C#中实现打印时显示提示消息
嘿,作为C#新手碰到这个需求完全不用慌,我来给你拆解一下怎么实现这个功能。其实C#的System.Drawing.Printing命名空间里已经提供了现成的事件来帮我们监听打印的开始和结束状态,正好用来显示提示消息。
核心思路
我们可以借助PrintDocument类,它有两个关键事件来触发提示:
BeginPrint:打印作业启动时触发,这时可以弹出“文档正在打印中”的提示EndPrint:打印作业完成(无论成功还是被取消)时触发,用来提示打印结果
下面我分两种常见场景给你写示例代码,你可以根据自己的项目类型选:
WinForms程序示例(最常用场景)
假设你有一个WinForm窗口,里面放了一个打印按钮,代码可以这么写:
using System; using System.Drawing.Printing; using System.Windows.Forms; namespace PrintNotificationDemo { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void printBtn_Click(object sender, EventArgs e) { // 创建打印文档实例 PrintDocument printDoc = new PrintDocument(); // 绑定打印状态的事件处理方法 printDoc.BeginPrint += OnPrintStarted; printDoc.EndPrint += OnPrintFinished; // 绑定打印内容的事件(你可以自定义要打印的内容) printDoc.PrintPage += OnPrintPage; // 弹出打印设置对话框,让用户选择打印机 PrintDialog printDialog = new PrintDialog(); printDialog.Document = printDoc; if (printDialog.ShowDialog() == DialogResult.OK) { // 确认后开始打印 printDoc.Print(); } } // 打印开始时触发的方法 private void OnPrintStarted(object sender, PrintEventArgs e) { MessageBox.Show("文档正在打印,请稍候...", "打印提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } // 打印结束时触发的方法 private void OnPrintFinished(object sender, PrintEventArgs e) { if (e.Cancel) { MessageBox.Show("打印已取消", "打印提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { MessageBox.Show("打印已完成!", "打印提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } // 定义要打印的内容(这里是示例文本) private void OnPrintPage(object sender, PrintPageEventArgs e) { e.Graphics.DrawString("这是打印的测试内容", new Font("Arial", 12), Brushes.Black, new PointF(10, 10)); // 如果有多页,设置e.HasMorePages = true,单页就设为false e.HasMorePages = false; } } }
控制台程序示例
如果是控制台项目,逻辑类似,只是用控制台输出代替弹窗:
using System; using System.Drawing.Printing; namespace ConsolePrintDemo { class Program { static void Main(string[] args) { PrintDocument printDoc = new PrintDocument(); printDoc.BeginPrint += OnPrintStarted; printDoc.EndPrint += OnPrintFinished; printDoc.PrintPage += OnPrintPage; // 直接启动打印(控制台程序可以跳过打印对话框) printDoc.Print(); Console.ReadLine(); } private static void OnPrintStarted(object sender, PrintEventArgs e) { Console.WriteLine("📄 文档正在打印中,请稍候..."); } private static void OnPrintFinished(object sender, PrintEventArgs e) { if (e.Cancel) { Console.WriteLine("⚠️ 打印已取消"); } else { Console.WriteLine("✅ 打印已完成!"); } } private static void OnPrintPage(object sender, PrintPageEventArgs e) { e.Graphics.DrawString("控制台打印测试内容", new Font("Arial", 12), System.Drawing.Brushes.Black, 10, 10); e.HasMorePages = false; } } }
小提示
- 如果用的是.NET Core/.NET 5+版本,记得先安装
System.Drawing.CommonNuGet包,这个命名空间在新版框架里是单独的包 - 测试的时候可以用Windows自带的“Microsoft Print to PDF”虚拟打印机,不用浪费纸张~
这样你就能在打印的不同阶段看到对应的提示消息啦,有不清楚的地方随时问!
内容的提问来源于stack exchange,提问作者user9631826
相关产品推荐
相关产品推荐

