从另一个窗口获取像素颜色的C#代码

7
我想从另一个窗口获取像素颜色。我现在有的代码是:

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

sealed class Win32
{
    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);
    
    [DllImport("user32.dll")]
    static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
    
    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
    
    static public System.Drawing.Color GetPixelColor(int x, int y)
    {
        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(IntPtr.Zero, hdc);
        Color color = Color.FromArgb((int)(pixel & 0x000000FF),
            (int)(pixel & 0x0000FF00) >> 8,
            (int)(pixel & 0x00FF0000) >> 16);
        return color;
    }
}

问题在于这段代码正在扫描整个屏幕,而这不是我想要的。我的想法是修改代码,根据另一个应用程序的屏幕边界来扫描像素颜色。也许可以使用 FindWindowGetWindow 进行操作?提前感谢。

1个回答

5

您可以按照您所说的导入FindWindow函数,通过窗口标题查找窗口:

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

static IntPtr FindWindowByCaption(string caption)
{
    return FindWindowByCaption(IntPtr.Zero, caption);
}

然后,向您的GetPixelColor函数添加一个额外的参数作为处理程序:
static public System.Drawing.Color GetPixelColor(IntPtr hwnd, int x, int y)
{
    IntPtr hdc = GetDC(hwnd);
    uint pixel = GetPixel(hdc, x, y);
    ReleaseDC(hwnd, hdc);
    Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                    (int)(pixel & 0x0000FF00) >> 8,
                    (int)(pixel & 0x00FF0000) >> 16);
    return color;
}

使用方法:

var title = "windows caption";

var hwnd = FindWindowByCaption(title);

var pixel = Win32.GetPixelColor(hwnd, x, y);

1
这个方法的一个大问题(对于任何想要扫描整个屏幕而不是 OP 的人来说)是它使用了许多 P/Invoke 调用,效率低下。如果你要用它处理超过几个像素,它会变得太慢。你可以将整个图像传输到 Bitmap 对象中,然后访问 scan0 指针以获得更快的速度。https://dev59.com/xnNA5IYBdhLWcg3wn_Q1#911225 - marknuzz
离题了,但是可以进一步阅读为什么GetPixel很慢,包括评论中的有趣替代方案:https://devblogs.microsoft.com/oldnewthing/20211223-00/?p=106050 - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接