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);
}
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
@Rob Relyea
Great suggestion. I will whip something up.
Finished whipping something up:
https://elegantcode.com/2010/12/13/wpfcopy-uielement-to-clipboard-as-multiple-formats/
the paste functionality does not work with non microsoft applications. Any idea why?
found the answer – mighty tricky to locate, so here it is for anyone else suffering the same problem:
http://openoffice.org/bugzilla/show_bug.cgi?id=85661
in essence you need to eat the bitmapfileheader for non .net apps to understand whats on the clipboard..