I have the following code that takes a Control (as a Visual object), uses a Visual Brush to pain the control into a RenderTargetBitmap which can then be saved to disk. This is successful.
I would like to use the same code to place the image in the clipboard. This does not seem to work; although the clipboard accepts the data, it does not accept that the data is an image. This is clearly a formatting issue but I have no idea how to sort it...
The code follows:-
public void CopyToClipBoard(Visual forDrawing)
{
RenderTargetBitmap bmp = ControlToImage(forDrawing, 96, 96);
CopyToClipBoard(bmp);
}
private void CopyToClipBoard(BitmapSource bmp)
{
Thread thread = new Thread(() =>
{
Clipboard.SetImage(bmp);
});
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
}
private static RenderTargetBitmap ControlToImage(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
}
// render control content
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX, dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), bounds.Size));
}
rtb.Render(dv);
return rtb;
}