显示用户打印预览并在打印时执行代码

时间:2013-12-08 23:23:08

标签: c# .net winforms bitmap print-preview

我有一个位图,我希望用户在打印之前看到它。所以我打开他的打印预览,如果用户决定打印,我想执行一些代码。

问题是,printPreviewDialog不会返回答案。这可能是因为它只有一个打印按钮和关闭按钮,但没有打印和关闭,所以我可以知道用户决定打印。

如果您有解决方案,我会很高兴,如果您认为这不是最佳方式,请告诉我。

代码:

        PrintDocument pd = new PrintDocument();
        pd.PrintPage += new PrintPageEventHandler(Print_Page);
        PrintPreviewDialog pritdlg = new PrintPreviewDialog();
        pritdlg.Document = pd;

        if (pritdlg.ShowDialog() == DialogResult.OK)
            pd.Print();
        else
            MessageBox.Show("you have canceled print");


        private void Print_Page(object o, PrintPageEventArgs e)
        {
        e.Graphics.DrawImage(target, 0,0);
        }

1 个答案:

答案 0 :(得分:2)

订阅您要发送到EndPrint控件的文档的printPreviewDialog事件,然后查看其PrintAction参数中的PrintEventArgs

示例:

private void buttonPrintPreview_Click(object sender, EventArgs e)
    {
        PrintPreviewDialog printDialog = new PrintPreviewDialog();
        printDialog.Document = yourDocument;
        yourDocument.EndPrint += doc_EndPrint; // Subscribe to EndPrint event of your document here.
        printDialog.ShowDialog();
    }

    void doc_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {
        if (e.PrintAction == System.Drawing.Printing.PrintAction.PrintToPrinter)
        {
            // Printing to the printer!
        }
        else if (e.PrintAction == System.Drawing.Printing.PrintAction.PrintToPreview)
        {
            // Printing to the preview dialog!
        }
    }