C#屏幕截图-窗口中为颜色检查,不是全屏显示

问题描述 投票:0回答:1

我目前在C#中有一个代码,可从特定位置(光标位置)获取颜色。它运作良好,但以某种方式需要全屏“截屏”,而不仅仅是特定窗口。因此,如果我在监视的窗口上方还有其他窗口,则会得到错误的颜色代码。有没有简单的方法可以修改它以仅检查特定窗口的“屏幕快照”,而不是全屏屏幕?这是

namespace MyApp
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    internal class Screeny
    {
        private IntPtr window;

        public Bitmap CaptureFromScreen(Rectangle rect)
        {
            Bitmap image = !(rect == Rectangle.Empty) ? new Bitmap(rect.Width, rect.Height) : new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(image);
            if (rect == Rectangle.Empty)
            {
                graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, image.Size, CopyPixelOperation.SourceCopy);
                return image;
            }
            graphics.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size, CopyPixelOperation.SourceCopy);
            return image;
        }

        public bool ExpectColor(Point p, string rgb)
        {
            Color colorFromScreen = this.GetColorFromScreen(p);
            string[] strArray = rgb.Split(new char[] { '.' });
            return (((colorFromScreen.R.ToString() == strArray[0]) && (colorFromScreen.G.ToString() == strArray[1])) && (colorFromScreen.B.ToString() == strArray[2]));
        }

        public Color GetColorFromScreen(Point p)
        {
            Bitmap bitmap = this.CaptureFromScreen(new Rectangle(p, new Size(2, 2)));
            Color pixel = bitmap.GetPixel(0, 0);
            bitmap.Dispose();
            return pixel;
        }

        public void setWindow(IntPtr window)
        {
            this.window = window;
        }
    }
}
c# screenshot
1个回答
1
投票

您需要获取要捕获的窗口Rect。要完成此任务,您需要一个结构Rect和一个可以获取窗口Rect的方法:

[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

下一步,只需使用它:

public static Bitmap GetWindowScreenshotOfProcess(Process process)
{
    var rect = new Rect();
    GetWindowRect(process.MainWindowHandle, ref rect); // filling rect object

    int width = rect.right - rect.left;
    int height = rect.bottom - rect.top;

    if (width <= 0 || height <= 0)
    {
        return null;
    }

    // Just for example, window screenshot export:

    var bmp = new Bitmap(width, height);
    var graphics = Graphics.FromImage(bmp);
    graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
    graphics.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
    bmp.Save("c:\\temp\\window_screen.png");
    return bmp;
}

此解决方案只能获取前景窗口的屏幕截图。如果目标窗口前面还有其他窗口,则需要使用内部WinAPI函数,例如正确提到的@ vasily.sib。

© www.soinside.com 2019 - 2024. All rights reserved.