2009-04-15 97 views
25

如何使用c#獲取X,Y像素的顏色?如何使用c#獲得X,Y像素的顏色?

至於結果,我可以將結果轉換爲我需要的顏色格式。我確信有這個API調用。

「對於監視器上的任何給定的X,Y,我想獲取該像素的顏色。」

+0

在屏幕上或者在您的應用程序窗口這個地方? – ChrisF 2009-04-15 18:48:53

+0

只是一般的顯示。我不關心任何特定的事例。 – MichaelICE 2009-04-15 18:53:56

+0

對於監視器上的任何給定的X,Y,我想獲取該像素的顏色。 – MichaelICE 2009-04-15 18:55:10

回答

36

要從屏幕得到一個像素的顏色這裏的代碼Pinvoke.net

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; 
     } 
    } 
10

Bitmap.GetPixel爲圖像...是你在追求什麼?如果不是,你能說出你的哪個x,y值嗎?在控制?

請注意,如果你意味着圖像,你想獲得大量像素,你不介意與不安全的代碼工作,那麼Bitmap.LockBits會比很多調用快很多GetPixel

+0

我需要它從當前的顯示,而不是一個特定的文件,或油漆盒的實例。 – MichaelICE 2009-04-15 18:52:55

2

除了從P/Invoke的解決方案,你可以使用Graphics.CopyFromScreen從屏幕上的圖像數據進入一個圖形對象。如果您不擔心可移植性,我會推薦P/Invoke解決方案。

1

在WPF參考:(PointToScreen的使用)

System.Windows.Point position = Mouse.GetPosition(lightningChartUltimate1); 

    if (lightningChartUltimate1.ViewXY.IsMouseOverGraphArea((int)position.X, (int)position.Y)) 
    { 
     System.Windows.Point positionScreen = lightningChartUltimate1.PointToScreen(position); 
     Color color = WindowHelper.GetPixelColor((int)positionScreen.X, (int)positionScreen.Y); 
     Debug.Print(color.ToString()); 


     ... 

     ... 


public class WindowHelper 
{ 
    // ****************************************************************** 
    [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.Windows.Media.Color GetPixelColor(int x, int y) 
    { 
     IntPtr hdc = GetDC(IntPtr.Zero); 
     uint pixel = GetPixel(hdc, x, y); 
     ReleaseDC(IntPtr.Zero, hdc); 
     Color color = Color.FromRgb(
      (byte)(pixel & 0x000000FF), 
      (byte)((pixel & 0x0000FF00) >> 8), 
      (byte)((pixel & 0x00FF0000) >> 16)); 
     return color; 
    } 
相關問題