如何从窗口获取屏幕截图?

时间:2020-02-08 22:45:18

标签: c#

我在抓取窗口的屏幕截图时遇到了麻烦。

这是我正在使用的代码:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace Alerts
{
    class ImgSearch
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string strClassName, string strWindowName);
        [DllImport("user32.dll")]
        public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);

        public struct Rect
        {
            public int Left { get; set; }
            public int Top { get; set; }
            public int Right { get; set; }
            public int Bottom { get; set; }
        }

        public static void ScreenShotWindow(IntPtr whandle)
        {
            // Get the window rectangle
            Rect window = new Rect();
            GetWindowRect(whandle, ref window);

            // Get window size
            int width = window.Right - window.Left;
            int height = window.Bottom - window.Top;
            Size size = new Size();
            size.Width = width;
            size.Height = height;

            //Create a new bitmap.
            var bmpScreenshot = new Bitmap(width,
                                           height,
                                           PixelFormat.Format32bppArgb);

            // Create a graphics object from the bitmap.
            var gfxScreenshot = Graphics.FromImage(bmpScreenshot);                

            // Take the screenshot from the upper left corner to the right bottom corner.
            gfxScreenshot.CopyFromScreen(window.Left,
                                        window.Right,
                                        0,
                                        0,
                                        size,
                                        CopyPixelOperation.SourceCopy);

            // Save the screenshot to the specified path that the user has chosen.
            bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
        }
    }
}

这是结果:

enter image description here

因此您可以看到图像为空,我希望得到这样的图像:

enter image description here

我100%确信窗口句柄不是问题,因为GetWindowRect可以正常工作

1 个答案:

答案 0 :(得分:5)

代码中有一个小错误,很容易被忽略。

gfxScreenshot.CopyFromScreen(window.Left,
  window.Top, // window.Top instead of window.Right
  0,
  0,
  size,
  CopyPixelOperation.SourceCopy);

您应在此处使用window.Right而不是window.Top。第二个参数是区域的Y坐标。