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:
Code:
using System.Windows.Forms;
class MyPanel : Panel {
public MyPanel() {
SetStyle( ControlStyles.SupportsTransparentBackColor, false );
SetStyle( ControlStyles.AllPaintingInWmPaint, true );
SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
UpdateStyles();
}
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:
Code:
System.ArgumentException was unhandled
HResult=-2147024809
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
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.