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

标签 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% 确信中间屏幕像素是红色。

最佳答案

内容:

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

相关文章:

php - 计算最接近盲人友好的颜色?

macos - 使用 Cocoa 在辅助显示器上全屏显示 macOS 窗口

c# - 在 asp.net web 表单中获取消息的网页导航被取消

c# - linq 查询是否可以更改其数据源,即字典的内容?

c# - 如何在 C# 中使 Dropdownlist 只读

colors - 显示 gnuplot 默认线条样式

java - 如何将十六进制颜色代码分配给java类文件中的任何数据类型

javascript - 根据高度计算纵横比宽度

c# - 用C#处理HTML文档