Max Max - 1 year ago 84
C# Question

Print Windows form in c#

I am trying to print a form using this code:

private void btnPrint_Click(object sender, EventArgs e)
Graphics g1 = this.CreateGraphics();
Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
Graphics g2 = Graphics.FromImage(MyImage);
IntPtr dc1 = g1.GetHdc();
IntPtr dc2 = g2.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
MyImage.Save(@"c:\PrintPage.jpg", ImageFormat.Jpeg);
FileStream fileStream = new FileStream(@"c:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
if (System.IO.File.Exists(@"c:\PrintPage.jpg"))

But is gives me an error at: MyImage.Save.

The error:

ExternalException was Unhandled: A generic error occurred in GDI+.

Can someone give me a fix for this problem,and explain, why I'am getting this error?

Thanks in Advance!

Answer Source
    private void btn_print_Click(object sender, EventArgs e)
        printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);

    Bitmap memoryImage;

    private void CaptureScreen()
        Graphics myGraphics = this.CreateGraphics();
        Size s = this.Size;
        memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
        Graphics memoryGraphics = Graphics.FromImage(memoryImage);
        memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)


    private void printDocument1_PrintPage_1(object sender, PrintPageEventArgs e)
        e.Graphics.DrawImage(memoryImage, 0, 0);

Add a print_document by dragging it from the toolbox to form. Execute this code, it will work fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download