I have a function to capture the screenshot of a WPF control:
public System.Drawing.Bitmap CaptureScreenshot()
{
Point p = this.PointToScreen(new Point(0, 0));
System.Drawing.Rectangle rc = new System.Drawing.Rectangle((int)p.X, (int)p.Y, (int)this.ActualWidth, (int)this.ActualHeight);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(rc.Width, rc.Height);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
g.CopyFromScreen(rc.Location, System.Drawing.Point.Empty, rc.Size);
}
return bitmap;
}
This is working fine in Win7. However, in Win8, if this function is called from a context menu, the captured screenshot also shows the context menu. It is not waiting for my context menu to disappear before it's taking the screenshot.
Why it's working in Win7 but not Win8? How do I wait until context menu disappears before taking the screenshot? I tried several things like DoEvents
or UpdateLayout()
but they don't seem to help.
UPDATE: Following pushpraj's comment, I got it working using RenderTargetBitmap:
var bitmap = new RenderTargetBitmap((int)grid.ActualWidth, (int)grid.ActualHeight, 96, 96, PixelFormats.Default);
bitmap.Render(grid);
Clipboard.SetImage(bitmap);
It seems to be working except one issue. My control has a light background, which turns into full black when I paste the clipboard. If I save the bitmap to a file directly, I don't have this problem. What's wrong?
UPDATE 2:
Okay, for the background problem using RenderTargetBitmap
, I found a fix at here.