PDFsharp & MigraDoc Foundation

XGraphics improperly disposes System.Drawing.Graphics object
Page 1 of 1

Author:  SWB [ Wed Aug 12, 2015 5:20 am ]
Post subject:  XGraphics improperly disposes System.Drawing.Graphics object

XGraphics.FromGraphics(...) takes a (pre-existing) System.Drawing.Graphics as an argument.

Since XGraphics was not responsible for creating the Graphics object, it should not try to dispose of it in XGraphics.Dispose(...). But it does just that in PDFsharp-gdi 1.50.3638-beta.

I discovered this when trying to use PDFsharp to render an owner-drawn, subclassed System.Windows.Forms.Panel. If I have not enabled double-buffering for the Panel, it does work (despite the bug), but the application crashes if double-buffering is enabled.

My code looks like this:
using System.Windows.Forms;

class MyPanel : Panel {
    public MyPanel() {
        SetStyle( ControlStyles.SupportsTransparentBackColor, false );
        SetStyle( ControlStyles.AllPaintingInWmPaint, true );
        SetStyle( ControlStyles.OptimizedDoubleBuffer, true );

    protected override void OnPaint( PaintEventArgs e ) {
        var pageSizePoints = new XSize( ... );

        using ( var xg = XGraphics.FromGraphics( g, pageSizePoints ) ) {
            // Drawing code

Because XGraphics.Dispose() disposes the passed Graphics object, this code produces the following ArgumentException:
System.ArgumentException was unhandled
  Message=Parameter is not valid.
       at System.Drawing.Graphics.GetHdc()
       at System.Drawing.BufferedGraphics.RenderInternal(HandleRef refTargetDC, BufferedGraphics buffer)
       at System.Drawing.BufferedGraphics.Render()
       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.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

The crash is avoided if SetStyle( ControlStyles.OptimizedDoubleBuffer, true ) is commented out.

Author:  Thomas Hoevel [ Wed Aug 12, 2015 9:15 am ]
Post subject:  Re: XGraphics improperly disposes System.Drawing.Graphics ob

Yes, it's a bug.
We'll fix it with the next release.

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group