Possible Duplicate:
Print Windows form in c#
I need to print the form where the print button is on:
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);
g1.ReleaseHdc(dc1);
g2.ReleaseHdc(dc2);
MyImage.Save(@"c:\PrintPage.jpg", ImageFormat.Jpeg);
FileStream fileStream = new FileStream(@"c:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
StartPrint(fileStream, "Image");
fileStream.Close();
if (System.IO.File.Exists(@"c:\PrintPage.jpg"))
{
System.IO.File.Delete(@"c:\PrintPage.jpg");
}
}
But is gives me an error at: MyImage.Save.
The error is: ExternalException was Unhandled: A generic error occurred in GDI+.
Can someone give me a fix for this problem,and explain, why I’m getting this error?
The exception message is crappy but indicates that GDI+ cannot write the file.
There are at least two problems. First off, a program is not allowed to write to c:\ without having admin privileges on Vista, Win7 and Win8 obtained through a UAC prompt. Or any non-admin account on previous Windows versions. Use Path.GetTempFileName() instead.
Second one is that you are sloppy about disposing MyImage. That will very likely make your program fail the second time you run this code since the file is still in use and the garbage collector didn’t get around to finalize the image object yet. Image.Dispose() is required to release the lock on the image file. Use the using statement to ensure it is consistently disposed.