winforms - Out of memory exception in CreateGraphics (GdipCreateFromHWND) -
on machines vary in configuration (os, graphics card , memory) outofmemory exception. tests showed there no significant increase in virtual memory consumed. that's piece of code exception raised:
public override size getpreferredsize(size proposedsize) { try { using (graphics g = this.creategraphics()) { sizef measured = g.measurestring(this.text, this.font); // <= outofmemoryexception measured += new sizef(1, 1); return measured.tosize(); } } catch (outofmemoryexception oom) { system.diagnostics.trace.writeline(oom.tostring()); } return proposedsize; }
the class derived directly label.
creategraphics() makes call gdi+ function gdipcreatefromhwnd in cases return status (3) raises outofmemoryexception face:
[editorbrowsable(editorbrowsablestate.advanced), securitypermission(securityaction.linkdemand, flags=securitypermissionflag.unmanagedcode)] public static graphics fromhwndinternal(intptr hwnd) { intptr 0 = intptr.zero; int status = safenativemethods.gdip.gdipcreatefromhwnd(new handleref(null, hwnd), out zero); if (status != 0) { throw safenativemethods.gdip.statusexception(status); // status = 3 throws outofmemoryexception text "out of memory" } return new graphics(zero); }
but unfortunately have not found documentation on function , cases when returns out of memory.
the issue @ least repeatable on 1 customers machine fast. has click on button creates new window 1 of derived label placed , used display content in webbrowser control.
if have ideas me find reasons of exception great!
cheers, michael
this might work:
private graphics _graphics; protected override void onpaint(painteventargs e) { _graphics = e.graphics; base.onpaint(e); } public override size getpreferredsize(size proposedsize) { try { sizef measured = _graphics.measurestring(this.text, this.font); measured += new sizef(1, 1); return measured.tosize(); } catch (outofmemoryexception oom) { system.diagnostics.trace.writeline(oom.tostring()); } return proposedsize; }
the documentation @ http://msdn.microsoft.com/en-us/library/system.windows.forms.control.creategraphics.aspx states "you cannot cache graphics object reuse, except use non-visual methods graphics.measurestring", trying do. fail if getpreferredsize called before control painted, , you'll want dispose graphics object, maybe closer viable solution.
Comments
Post a Comment