在C#(全屏游戏)中获取中间屏幕像素(颜色)?

时间:2012-06-23 18:52:18

标签: c# colors fullscreen pixel intptr

我正在运行全屏游戏,我正在尝试找出中间像素的颜色。然而,我使用的代码似乎只适用于窗口应用程序/游戏/等。这是我的代码:

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%肯定中间屏幕像素是红色。

1 个答案:

答案 0 :(得分:3)

关键词:

//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);