1

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.

Community
  • 1
  • 1
newman
  • 6,841
  • 21
  • 79
  • 126
  • Try [RenderTargetBitmap](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap(v=vs.110).aspx) to render the same on a bitmap instead of capturing from the screen. – pushpraj Sep 22 '14 at 03:29
  • Thanks for the tip. However, I ran into another problem that the control's light background becomes black, see my updated question above. – newman Sep 22 '14 at 14:07
  • Could you post some sample xaml, may I give a try. – pushpraj Sep 22 '14 at 14:40
  • I got the fix now, see my updated question above. Thank you very much! – newman Sep 22 '14 at 15:47

0 Answers0