1. 程式人生 > >C#獲取某座標的顏色

C#獲取某座標的顏色

C# 獲取某座標的顏色:

這個獲取的方法是基於螢幕獲取的如果要基於我們的winfrom軟體獲取的話,就要加個演算法計算這個東西。那麼可以參考文章:

直接呼叫我們的 GetPixelColor(); 這個方法傳入座標點就OK了

得到的結果

我們會得到一個ARGB的值

獲取某座標的顏色的核心程式碼:

 #region 獲取某座標的顏色
 private struct POINT
 {
     private int x;
     private int y;
 }
 static POINT point;

 [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
 private static extern int GetDC(int hwnd);
 [DllImport("gdi32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
 private static extern int GetPixel(int hdc, int x, int y);
 [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
 private static extern int ReleaseDC(int hwnd, int hdc);
 [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
 private static extern int WindowFromPoint(int x, int y);
 [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
 private static extern int ScreenToClient(int hwnd, ref POINT lppoint);

 //獲取螢幕指定座標點的顏色
 public static Color GetPixelColor(int x, int y)
 {
     int h = WindowFromPoint(x, y);
     int hdc = GetDC(h);

     ScreenToClient(h, ref point);
     int c = GetPixel(hdc, x, y);
     return Color.FromArgb(c);
 }

 #endregion