WPF – Copy UIElement as Image to Clipboard

Category:UncategorizedTag: , :

This is a question to all the WPF developers out there.  Have you ever wanted to take a snapshot of a UIElement in your WPF application, such as a control or a section of a view, and use to generate a preview or copy it to the clipboard so your user can paste it somewhere else?  If you have, then I may have a simple solution for you.

The following code snippet does just that.  It simply creates an image from a UIElement (including all its children) and copies it to the clipboard.  Now the user can paste (ctrl+v) it anywhere they like.

/// <summary>
/// Copies a UI element to the clipboard as an image.
/// </summary>
/// <param name="element">The element to copy.</param>
public static void CopyUIElementToClipboard(FrameworkElement element)
{
    double width = element.ActualWidth;
    double height = element.ActualHeight;
    RenderTargetBitmap bmpCopied = new RenderTargetBitmap((int)Math.Round(width), (int)Math.Round(height), 96, 96, PixelFormats.Default);
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        VisualBrush vb = new VisualBrush(element);
        dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
    }
    bmpCopied.Render(dv);
    Clipboard.SetImage(bmpCopied);
}

5 thoughts on “WPF – Copy UIElement as Image to Clipboard

  1. Brian-
    Love that.
    Might be interesting to show converting this “data” to both an image and a nice text represeentation, as when you use the clipboard, ideally, several formats are offered.
    I like to imagine the scenario of a listboxitem with a rich datatemplate. Perhaps a tweet in a twitter client…

    Thanks, Rob
    WPF Team

Comments are closed.