为了账号安全,请及时绑定邮箱和手机立即绑定

如何阅读屏幕像素的颜色

如何阅读屏幕像素的颜色

C#
慕桂英3389331 2019-09-02 08:19:14
好的,我正在寻找能够读取显示器上某个像素颜色的功能或其他功能,当检测到该颜色时,将启用另一个功能。我想用RGB。所有帮助赞赏。谢谢。
查看完整描述

3 回答

?
Helenr

TA贡献1780条经验 获得超3个赞

这里的大多数答案都使用该像素的相同来源(桌面直流)。

关键功能是GetPixel。


[DllImport("user32.dll", SetLastError = true)]

public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll", SetLastError = true)]

public static extern IntPtr GetWindowDC(IntPtr window);

[DllImport("gdi32.dll", SetLastError = true)]

public static extern uint GetPixel(IntPtr dc, int x, int y);

[DllImport("user32.dll", SetLastError = true)]

public static extern int ReleaseDC(IntPtr window, IntPtr dc);


public static Color GetColorAt(int x, int y)

{

    IntPtr desk = GetDesktopWindow();

    IntPtr dc = GetWindowDC(desk);

    int a = (int) GetPixel(dc, x, y);

    ReleaseDC(desk, dc);

    return Color.FromArgb(255, (a >> 0) & 0xff, (a >> 8) & 0xff, (a >> 16) & 0xff);

}

我认为这是最干净,最快捷的方式。


注意:


如果您在Windows上的“显示设置”中修改了默认文本大小以提高高分辨率显示屏的可读性,则需要以相同的方式调整GetPixel()的坐标参数。例如,如果光标位置为(x,y),在Windows 7上具有150%的文本大小,则需要调用GetPixel(x * 1.5,y * 1.5)以获取光标下像素的颜色。


查看完整回答
反对 回复 2019-09-02
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

此功能更短,并且可以在System.Drawing没有Pinvoke的情况下使用相同的结果。


Bitmap bmp = new Bitmap(1, 1);

Color GetColorAt(int x, int y)

{

    Rectangle bounds = new Rectangle(x, y, 1, 1);

    using (Graphics g = Graphics.FromImage(bmp))

        g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);

    return bmp.GetPixel(0, 0);

}


查看完整回答
反对 回复 2019-09-02
  • 3 回答
  • 0 关注
  • 411 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信