如何阅读屏幕像素的颜色

好的,我正在寻找能够读取显示器上某个像素颜色的功能或其他功能,当检测到该颜色时,将启用另一个功能。我想用RGB。所有帮助赞赏。谢谢。



慕桂英3389331
浏览 415回答 3
3回答

Helenr

这里的大多数答案都使用该像素的相同来源(桌面直流)。关键功能是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)以获取光标下像素的颜色。

收到一只叮咚

此功能更短,并且可以在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);}
打开App,查看更多内容
随时随地看视频慕课网APP