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);
}
/// 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);
}
[…] about a week ago I wrote a post showing how to Copy a WPF UIElement as an Image to the Clipboard. In reply to that post Rob Relyea made a comment regarding supporting multiple formats on the […]
Works great! Thanks so much!
You’re welcome. I am glad you found it useful.