I'm trying to create a graphics object that I can use to draw a metafile and I'm not sure what is the best way to do it. Ultimately the metafiles will be included in a Word document and we are looking to have them look good when printed.
At first I had something like this:
var ms = new MemoryStream();
using (var mfG = System.Drawing.Graphics.FromHwndInternal(IntPtr.Zero))
using (Metafile mf = new Metafile(ms, mfG.GetHdc(), EmfType.EmfPlusOnly, "Chart"))
using (var g = System.Drawing.Graphics.FromImage(mf))
{
// do some drawing
}
And this works, but I want to process multiple images in parallel and in that case it will generate errors because they are all trying to use the same graphics object.
So I tried (based on some suggestions on line to create a graphics object):
using (var mfG = new System.Drawing.Printing.PrinterSettings().CreateMeasurementGraphics())
But it still has the same problem. Apparently CreateMeasurementGraphics
gives you the same graphics object every time.
I can wrap the code with a lock
to make other threads wait. And maybe I should. But is there a better way to generate independent Graphics
objects that will produce decent printable metafiles?