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);
}

Brian Lagunas

View all posts

3 comments

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.