2012-04-13 79 views
3

我正在尋找像素顏色通過本網站上的職位,我碰到這樣的: How do I get the colour of a pixel at X,Y using c#?獲得實例

將這種方法仍然是有效的努力得到的只是表單內像素的顏色?

如果不是這樣,那麼將基本上「映射」二維色彩值數組中的表單的方法是什麼?

例如,我有一個Tron遊戲,我想查看lightbike的下一個位置是否已經包含另一個lightbike。

感謝, 伊恩

回答

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

我遇到了「返回Win32」行的問題。 Visual Studio希望將其更改爲Microsoft.Win32。我正在使用Visual Studio 2010.是否有我必須導入的庫或其他內容? – 2012-04-13 05:02:11

+0

對不起,我編輯了我的帖子。 – Bill 2012-04-13 05:07:47

+0

此解決方案不乾淨。 'IntPtr.Zero'將爲您提供桌面直流電,您的窗戶上可能有窗戶。更好:獲取想要的顏色來自控件的'Handle'屬性。 [比較](http://stackoverflow.com/a/24759418/1442225) – Bitterblue 2014-08-04 12:23:44

0

您可以使用GetPixel方法得到的顏色。

例如

//從圖像文件創建一個位圖對象。 位圖myBitmap =新位圖(「Grapes.jpg」);

//獲取myBitmap中像素的顏色。 Color pixelColor = myBitmap.GetPixel(50,50);

這可能是另一種方式來做到這一點的不同情況詳細click here

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; 
     } 
    } 
+0

使用這種方法,有沒有辦法快速「截圖」當前實例? – 2012-04-13 04:47:17

+0

有關屏幕截圖的信息http://stackoverflow.com/questions/1163761/c-sharp-capture-screenshot-of-active-window – Adil 2012-04-13 04:51:44

0

您參考來自您的形式得到了像素的顏色,你可以使用的方法從問題,你剛纔需要先確定像素是否位於表單的邊界內,並且需要將座標從表單轉換爲屏幕的座標,反之亦然。

編輯:經過一番思考,如果有人在窗體頂部打開另一個窗口,這將是不好的!最好弄清楚做這件事的不同方式,我認爲......