WPF - Graphics.CopyFromScreen returns a black image

前提是你 提交于 2020-01-01 02:33:28

问题


The following method is taken from a WinForms app. It simply captures the screen, but I needed to modify it to work in a WPF application. When I use it, it returns a black image. The dimensions are correct. I have not got any open DirectX or videos and it wouldn't work even on my desktop.

    public static Bitmap CaptureScreen()
    {
        // Set up a bitmap of the correct size

        Bitmap CapturedImage = new Bitmap((int)SystemParameters.VirtualScreenWidth,
            (int)SystemParameters.VirtualScreenHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        // Create a graphics object from it
        System.Drawing.Size size = new System.Drawing.Size((int)SystemParameters.VirtualScreenWidth, (int)SystemParameters.VirtualScreenHeight);

        using (Graphics g = Graphics.FromImage(CapturedImage))
        {
            // copy the entire screen to the bitmap
            g.CopyFromScreen((int)SystemParameters.VirtualScreenWidth, (int)SystemParameters.VirtualScreenHeight, 0, 0,
                size, CopyPixelOperation.SourceCopy);
        }
        return CapturedImage;
    }

Can anyone show me the error in my ways?


回答1:


I believe you need to use Interop and the BitBlt method. This blog explains how this is done, and a follow-on post that shows how to get window borders.




回答2:


I think the first two params to g.CopyFromScreen should be 0.

Here's code that works for me:

        var size = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
        var capture = new System.Drawing.Bitmap(size.Width, size.Height);

        var g = System.Drawing.Graphics.FromImage(capture);
        g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(size.Width, size.Height));
        g.Dispose();


来源:https://stackoverflow.com/questions/5708985/wpf-graphics-copyfromscreen-returns-a-black-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!