2012-06-23 45 views
2

我正在運行全屏遊戲,我試圖找出中間像素的顏色。然而,我使用的代碼似乎只適用於窗口化的應用程序/遊戲/等。這是我的代碼:獲取C#(全屏遊戲)中的中間屏幕像素(顏色)?

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

首先,你必須按相反的順序(BGR)的RGB參數。 –

+0

請不要發佈重複的問題:http://stackoverflow.com/questions/11173287/getting-a-pixel-from-the-screen-in-a-full-screen-game-c-windows –

+0

我的道歉,但我非常渴望儘快解決這個問題。我將刪除另一個。 – ZimZim

回答

2

關於什麼的:

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

對不起,對於遲到的回覆,但我正在做這個遊戲,並且這個方法被放入一個while循環中,每個循環之間延遲30ms,所以基本上每30ms我會拍攝一個使得遊戲滯後的快照(和我的整個電腦)。沒有其他辦法嗎? – ZimZim