By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,977 Members | 1,326 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,977 IT Pros & Developers. It's quick & easy.

Only able to print once?

P: n/a
I have a form with tab pages on it, and I'd like to print each page whenever
a button is pressed (all the tabpages share the same print button - I just
give it a different parent when another tab is pressed). But I can only print
once. When the print button is pressed the second time, I get error

An unhandled exception of type
'System.Runtime.InteropServices.ExternalException' occurred in
Additional information: A generic error occurred in GDI+.

I'm not sure what to do here. My code is below. I commented out the
pd.Print(); and it worked fine. No exceptions, and the bitmaps saved fine
each time. I also tried giving the PrintDocument a different name each time,
and it still isn't happy.
private void printClick(object sender, System.EventArgs e)
Graphics currentTab = this.CreateGraphics();
Size s = this.Size;
Bitmap memoryImage = new Bitmap(s.Width - 10, s.Height - 36, currentTab);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
IntPtr dc1 = currentTab.GetHdc();
IntPtr dc2 = memoryGraphics.GetHdc();
BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height,
dc1, 2, 2, 13369376);
CurrentPage = memoryImage;
CurrentPage.Save("sCurrentPage.bmp",System.Drawing .Imaging.ImageFormat.Bmp);

PrintDocument pd = new PrintDocument();
PageSetupDialog pg = new PageSetupDialog();
printDialog1.Document = pd;
pg.Document = pd;
pg.PageSettings.Landscape = true;
DialogResult result = printDialog1.ShowDialog();

if (result==DialogResult.OK)
{pd.PrintPage += new
System.Drawing.Printing.PrintPageEventHandler(Prin tCurrentPage); pd.Print();}
Thanks for any help!!!
May 12 '06 #1
Share this Question
Share on Google+
1 Reply

P: n/a
In case anyone needs it, the problem is in this line:

pd.PrintPage += new
System.Drawing.Printing.PrintPageEventHandler(Prin tCurrentPage);

PrintCurrentPage looked like this:

private void PrintCurrentPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
if (CurrentPage != null){CurrentPage = new Bitmap(@"C:\sCurrentPage.bmp");}
I found that "When a bitmap image is loaded from a file the file remains
locked open. This may be the root of the problem.
To overcome the file locking open the file on a stream, read the image from
the stream and explicitly close the stream."
So I changed PrintCurrentPage to look like this:
if (CurrentPage != null)
FileStream fs = File.Open(@"C:\sCurrentPage.bmp", FileMode.Open,
Bitmap bm = (Bitmap)Bitmap.FromStream(fs);
CurrentPage = bm;
e.Graphics.DrawImage(CurrentPage, 0, 0);
And it all worked fine.
May 12 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.