一、需求
用户点击打印后,弹出打印预览,用户关闭预览框后,询问是否打印,如果要打印则弹出打印框。(备注:打印内容只能是自定义的字符串,不支持指定文件夹打印)
二、实现代码
cs
using System.Drawing.Printing;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 触发打印预览按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
PrintPreview();
}
#region 打印相关方法
/// <summary>
/// 打印预览
/// </summary>
private void PrintPreview()
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
printPreviewDialog.Document = printDocument;
// 确认关闭预览框后
if (printPreviewDialog.ShowDialog() == DialogResult.Cancel)
{
// 询问用户是否打印
if (MessageBox.Show("您确定要打印吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
PrintContents();//弹出打印框
}
}
}
/// <summary>
/// 弹出打印框
/// </summary>
private void PrintContents()
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
PrintDocument printDocument = new PrintDocument();
printDocument.PrinterSettings = printDialog.PrinterSettings;
printDocument.PrintPage += new PrintPageEventHandler(PrintDocument_PrintPage);//打印对应的内容
printDocument.Print();
}
}
/// <summary>
/// 打印内容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Hello, World!", new Font("Arial", 12), Brushes.Black, 100, 100);
}
#endregion
}
}
三、代码小结
- 按钮点击事件 :
button1_Click
方法触发PrintPreview
方法。- 打印预览 :
PrintPreview
方法创建一个PrintDocument
对象并设置其PrintPage
事件处理程序。然后显示PrintPreviewDialog
,供用户预览打印内容。- 确认打印 :如果用户在预览对话框中点击了关闭,则弹出确认对话框询问是否打印。如果用户确认,则调用
PrintContents
方法。- 弹出打印框 :
PrintContents
方法显示PrintDialog
供用户选择打印机和设置。如果用户确认,则重新创建PrintDocument
对象,并设置打印机设置,最后调用- 打印内容 :
PrintDocument_PrintPage
方法定义了实际的打印内容,这里只是简单地打印 "Hello, World!"。