Feb 2, 2010

Convert WPF visuals to Windows metafile (WMF)

There's already a solution for this, you can convert both visual or UIElemnt to metafile... the only (and the biggest) drawback is that the metafile that you get is not vector because you are pasting an bmp inside it... here are the links:


and the visuals addon taken from the microsoft forums:

private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
if (target == null)
return null;

Rect bounds = VisualTreeHelper.GetDescendantBounds(target);

RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),

DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));


return rtb;

EDIT: if your visual/UIElement has transparent background, the code supplied above will make an image with black background... the workaround is to use the PngBitmapEncoder instead of BmpBitmapEncoder