API聲明:
/// <summary>/// 擷取指定視窗的裝置情境/// </summary>/// <param name="hwnd">將擷取其裝置情境的視窗的控制代碼。若為0,則要擷取整個螢幕的DC</param>/// <returns>指定視窗的裝置情境控制代碼,出錯則為0</returns>[DllImport("user32.dll")]public static extern IntPtr GetDC(IntPtr hwnd);/// <summary>/// 釋放由調用GetDC函數擷取的指定裝置情境/// </summary>/// <param name="hwnd">要釋放的裝置情境相關的視窗控制代碼</param>/// <param name="hdc">要釋放的裝置情境控制代碼</param>/// <returns>執行成功為1,否則為0</returns>[DllImport("user32.dll")]public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);/// <summary>/// 在指定的裝置情境中取得一個像素的RGB值/// </summary>/// <param name="hdc">一個裝置情境的控制代碼</param>/// <param name="nXPos">邏輯座標中要檢查的橫座標</param>/// <param name="nYPos">邏輯座標中要檢查的縱座標</param>/// <returns>指定點的顏色</returns>[DllImport("gdi32.dll")]public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
使用:
public Color GetColor(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;
}