Search code examples
c#wpfprintdialog

Implement print dialog in my code


I've been trying to solve this myself, but I haven't figured it out yet. I want to open a print dialog window when I'm pressing the btn_print button. I've called out one line I assume is not needed anymore as this is defining the size of the printed page.

Could anyone look at my code and tell me what I could do?

private void btn_print_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            PrintDocument pd = new PrintDocument();
            //pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            pd.Print();
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while printing", ex.ToString());
        }
    }

    private void pd_PrintPage(object sender, PrintPageEventArgs e)
    {

    }

Solution

  • Try something like this:

    PrintDocument pd = new PrintDocument();
    //pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
    pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
    
    System.Windows.Forms.PrintDialog p = new System.Windows.Forms.PrintDialog();
    p.Document = pd;
    if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        pd.Print();