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

标签 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 工作正常

最佳答案

代码中有一个很容易被忽视的小错误。

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

这里应该使用window.Top,而不是window.Right。第二个参数是区域的 Y 坐标。

关于c# - 如何从窗口获取屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131929/

相关文章:

c# - Linq 获取表中条目最多的员工的 ID

c# - 检测远程桌面连接

C# 从套接字读取错误的数据

c# - 为什么我的流式阅读器和编写器突然停止工作?

c# - 使用 MVC 的 REST Web 服务,是个好主意吗?

c# - 有没有一种方法可以像在 eclipse 中那样在 visual studio 2012 中生成 getter、setter 函数

c# - 在 C# WPF 中编写漂亮的收据以在热敏打印机 POS 上打印

c# - 获取 protected 字段的值

c# - 无法找到该资源。 MVC4

c# - 应用繁忙时显示沙漏