Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve the winforms error "A generic error occurred in GDI+. "?

I am facing the following exception in my C#.net win forms application.

A generic error occurred in GDI+.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawRectangle(Pen pen, Int32 x, Int32 y, Int32 width, Int32 height)
at WeifenLuo.WinFormsUI.Docking.DockWindow.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

The most confusing point is that, it occurs very rarely when the application loading a form (which contains some rich graphics, WPF work etc.), could say about 90% of the time the form is loaded successfully. but very few times it happens to be reproduced and also only on some machines, at some other machines this form is works 100% of the time and never face this exception.

I am not getting any idea why this exceptions happening, because it also not showing the exact stack trace which causes the exception. Please suggest if one have any idea about how to deal with it.

like image 969
M_Idrees Avatar asked Feb 20 '12 13:02

M_Idrees


People also ask

Could not save the PDF document a generic error occurred in GDI+?

2 Reasons Why This Generic GDI Error Occurred Due to the lock when you try to save and overwrite your modified bitmap, it throws this error. When you are saving a file, make sure the user has Write permission on the folder.


1 Answers

Your code is probably leaking GDI resources badly. Have a look with Taskmgr.exe, Processes tab. View + Select Columns and tick Handles, USER objects and GDI objects. Run your program and observe the displayed values for your process. A constantly climbing value for GDI objects spells trouble, the show is over when it reaches 10,000.

Exactly what might cause the leak is not quite that easy to diagnose. Although you can single-step your code in the debugger and keep an eye on the taskmgr number. The classic mistake is creating pens and brushes in a Paint event handler and not disposing them. Without the garbage collector running often enough to clean up. Use the using statement to fix.

like image 155
Hans Passant Avatar answered Sep 19 '22 23:09

Hans Passant