Skip to main content

C# - Getting from WPF to a Metafile & onto the Clipboard [Intermediate]


So in the world of Windows, there is this horribly awful and horribly useful thing called a metafile (sometimes called WMF, sometimes EMF). In general terms, it is essentially a transportable list of GDI commands for drawing an image or set of images. Applications like Microsoft Word use it for transferring collections of graphical objects to other applications through the clipboard or drag & drop. It has been around for quite a while, and so is supported as a standard clipboard/drag&drop format by many applications.

However, as soon as we enter the WPF world, we have a problem. WPF knows nothing about GDI - you can't convert from a WPF Visual into a list of GDI commands. So the very basic infrastructure of a metafile no longer meshes with the way WPF works. But don't give up yet!

While it isn't possible to go from a WPF visual to GDI commands, it is possible to go from a visual to a bitmap. And, thankfully, a bitmap can be placed inside of a metafile. Now, be warned, this is not a perfect solution - part of the usefulness of a metafile is that since it is just a list of GDI commands, it is (in many ways) a vectored image. By just sticking a bitmap in the metafile, that whole vectored concept goes out the window.

You are probably wondering "if you already have a bitmap in your hands, why not just stick that on the clipboard, instead of going to all the effort of creating a metafile?" (if you weren't, you should have been :P). The answer to that is two fold - one, sometimes applications deal with metafiles much better than a plain old bitmap (Microsoft Word in drag/drop, I'm looking at you!). Two, when a bitmap gets placed on the clipboard, any information about the DPI of that bitmap gets lost (because what gets placed on the clipboard is just the pixels - no header information is carried along). By using a metafile, information like DPI is kept with the image.

Ok, enough talk and complaining. Let's look at some code. It actually isn't that hard to do - it is just a matter of knowing what to do in the first place:
public static bool PlaceElementOnClipboard(UIElement element)
{
  bool success = true;
  Bitmap gdiBitmap = null;
  MemoryStream metafileStream = null;

  var wpfBitmap = MakeRenderTargetBitmap(element);
  try
  {
    gdiBitmap = MakeSystemDrawingBitmap(wpfBitmap);
    metafileStream = MakeMetafileStream(gdiBitmap);

    var dataObj = new DataObject();
    dataObj.SetData(DataFormats.Bitmap, gdiBitmap);
    dataObj.SetData(DataFormats.EnhancedMetafile, metafileStream);
    Clipboard.SetDataObject(dataObj, true);
  }
  catch
  { success = false; }
  finally
  {
    if (gdiBitmap != null)
    { gdiBitmap.Dispose(); }
    if (metafileStream != null)
    { metafileStream.Dispose(); }
  }

  return success;
}
 
That's the top level view of what we are doing. First, we create a RenderTargetBitmap out of the given UIElement. Then we convert that bitmap (the WPF kind) into the GDI kind (a System.Drawing.Bitmap). Once we have the GDI bitmap, we can create a metafile (or, in this case, create a MemoryStream containing the metafile).

Once we have everything created, it is time to create a DataObject and populate it. We push in both the GDI bitmap and the metafile stream to make sure that if an application supports one format, but not the other, the data on the clipboard will still be useful. After we have a populated data object, all that is left is to push it onto the clipboard, and then clean up after ourselves.

Creating the RenderTargetBitmap and the System.Drawing.Bitmap isn't that interesting - we have done it before here (you can check out thistutorial), but here is the code anyway:
private static RenderTargetBitmap MakeRenderTargetBitmap(UIElement element)
{
  element.Measure(new System.Windows.Size(double.PositiveInfinity, 
    double.PositiveInfinity));
  element.Arrange(new Rect(new System.Windows.Point(0, 0), 
    element.DesiredSize));
  RenderTargetBitmap rtb = new RenderTargetBitmap(
    (int)Math.Ceiling(element.RenderSize.Width), 
    (int)Math.Ceiling(element.RenderSize.Height), 
    96, 96, PixelFormats.Pbgra32);
  rtb.Render(element);
  return rtb;
}

private static Bitmap MakeSystemDrawingBitmap(RenderTargetBitmap wpfBitmap) 
{ 
  var encoder = new BmpBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(wpfBitmap));
  var stream = new MemoryStream(); 
  encoder.Save(stream); 

  var gdiBitmap = new Bitmap(stream);
  stream.Close();
  stream.Dispose();

  return gdiBitmap;
}
 
The interesting code is converting from the System.Drawing.Bitmap to the Metafile:
private static MemoryStream MakeMetafileStream(Bitmap image)
{
  Graphics graphics = null; 
  Metafile metafile= null; 
  var stream = new MemoryStream();
  try
  {
    using (graphics = Graphics.FromImage(image))
    {
      var hdc = graphics.GetHdc();
      metafile= new Metafile(stream, hdc);
      graphics.ReleaseHdc(hdc);
    }
    using (graphics = Graphics.FromImage(metafile))
    { graphics.DrawImage(image, 0, 0); }
  }
  finally
  {
    if (graphics != null)
    { graphics.Dispose(); }
    if (metafile!= null)
    { metafile.Dispose(); }
  } 
  return stream;
}
 
The gist here is that we pull the HDC (the Handle for Device Context) out of the Graphics object for the System.Drawing.Bitmap and use it to make a new metafile on top of a new memory stream we just created. Then we get the graphics object for the new metafile, and draw on it as much as we want (although in this case, all we want to do is draw the bitmap). Once we are done, we clean up, and are left with a MemoryStream that holds the metafile.

There you go! We successfully took a WPF element and got it onto the clipboard in a (rasterized) metafile. One random other thing to note before you grab the code file below and go on your way - don't forget to add a reference to the System.Drawing dll in your Visual Studio project - that is where the Metafile, Graphics, and Bitmap classes are defined.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as