我在搜索这个网站上的帖子时发现了这个: How do I get the colour of a pixel at X,Y using c#?
这种方法对于尝试获取表单内部像素的颜色是否仍然有效?
如果不是,有什么方法可以从根本上“映射”二维颜色值数组中的表单?
例如,我有一个 Tron 游戏,我想检查轻型摩托车的下一个位置是否已经包含另一辆轻型摩托车。
谢谢, 伊恩
最佳答案
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;
}
}
使用它,您可以执行以下操作:
public static class ControlExts
{
public static Color GetPixelColor(this Control c, int x, int y)
{
var screenCoords = c.PointToScreen(new Point(x, y));
return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
}
}
因此,在您的情况下,您可以:
var desiredColor = myForm.GetPixelColor(10,10);
关于c# - 在实例中获取像素颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135290/