3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個贊
這里的大多數(shù)答案都使用該像素的相同來源(桌面直流)。
關(guān)鍵功能是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);
}
我認(rèn)為這是最干凈,最快捷的方式。
注意:
如果您在Windows上的“顯示設(shè)置”中修改了默認(rèn)文本大小以提高高分辨率顯示屏的可讀性,則需要以相同的方式調(diào)整GetPixel()的坐標(biāo)參數(shù)。例如,如果光標(biāo)位置為(x,y),在Windows 7上具有150%的文本大小,則需要調(diào)用GetPixel(x * 1.5,y * 1.5)以獲取光標(biāo)下像素的顏色。

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個贊
此功能更短,并且可以在System.Drawing沒有Pinvoke的情況下使用相同的結(jié)果。
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);
}
- 3 回答
- 0 關(guān)注
- 445 瀏覽
添加回答
舉報