Show a user print preview and execute code if he printed

2.5k views Asked by At

I have a bitmap I want the user to see before he prints it. So I open for him print preview, if the user decides to print I want to execute some code.

The problem is, printPreviewDialog will not return an answer. This may be because it has only a print button and close button, but no print-and-close so I can know the user decided to print.

If you have a solution for that I'll be happy, if you think it's not the best way to do so please tell me.

code:

        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

There are 1 answers

0
Mitch On BEST ANSWER

Subscribe to the EndPrint event of the document you are sending to the printPreviewDialog control, then check the PrintAction in its PrintEventArgs argument.

Example:

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!
        }
    }