我正在运行一个全屏游戏,我试图找出中间像素的颜色。然而,我正在使用的代码似乎只适用于窗口应用程序/游戏/等。这是我的代码:
public static 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;
}
我得到的中间屏幕像素是这样的:
int ScreenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
int ScreenHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
那么如何使这段代码兼容全屏游戏呢?
它给我的 ARGB 值为 A = 255、R = 0、G = 0、B = 0
,即使我 100% 确信中间屏幕像素是红色。
最佳答案
内容:
//using System.Windows.Forms;
public static Color GetPixelColor(int x, int y)
{
Bitmap snapshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
using(Graphics gph = Graphics.FromImage(snapshot))
{
gph.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
}
return snapshot.GetPixel(x, y);
}
然后:
Color middleScreenPixelColor = GetPixelColor(Screen.PrimaryScreen.Bounds.Width/2, Screen.PrimaryScreen.Bounds.Height/2);
关于c# - 在C#(全屏游戏)中获取中屏像素(颜色)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172106/