1

I need to create some in-memory (not file-based) metafiles and display them. In the OnPaint handler of a panel on my form I call this code:

Metafile metafile;
using( Graphics offScreenGraphics = Graphics.FromHwndInternal( IntPtr.Zero ) )
{
    IntPtr hDC = offScreenGraphics.GetHdc();
    metafile = new Metafile( hDC, EmfType.EmfPlusDual );
    offScreenGraphics.ReleaseHdc();
}

Graphics graphics = Graphics.FromImage( metafile );
graphics.FillRectangle( Brushes.LightYellow, 0, 0, 100, 100 );
graphics.DrawLine( Pens.Red, 50, 50, 100, 100 );

e.Graphics.DrawImage( metafile, 50, 50 );

However, nothing is displayed and regardless of what I try to draw in the metafile, its PhysicalDimension is always something like 35x35, which is too small given that the units are hundredths of a millimeter!

NOTE: Of course this is a contrived example, I won't be creating a metafile just to draw some graphic in the same method. I need to pass the metafile around in my application. This is just a simple test to make sure I will be able to draw it with the DrawImage method.

crypto_rsa
  • 341
  • 1
  • 12

1 Answers1

2

OK, that was easy. From my original example I left out details which I thought were unnecessary, such as disposing the GDI objects I used. But in case of metafiles, it seems to be crucial to dispose the Graphics object you are drawing it with. Only after you do that, the metafile is "finished" and you can draw it (it also report a correct PhysicalDimension, by the way).

So the above code should be adjusted in this way:

using( Graphics graphics = Graphics.FromImage( metafile ) )
{
    graphics.FillRectangle( Brushes.LightYellow, 0, 0, 100, 100 );
    graphics.DrawLine( Pens.Red, 50, 50, 100, 100 );
}
crypto_rsa
  • 341
  • 1
  • 12
  • Yes, Graphics objects must always be created when you're gonna use them and disposed when you're done as they are rendered invalid for each WM_PAINT event that occurs. You can also call its Flush() method before disposing. –  Nov 01 '12 at 20:42
  • Ah, thanks for the `Flush` tip. I thought there is such a method but I couldn't recall its name. – crypto_rsa Nov 02 '12 at 10:37