编程语言
首页 > 编程语言> > C#_动态获取鼠标位置的颜色

C#_动态获取鼠标位置的颜色

作者:互联网

 

 

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


标签:IntPtr,场景,鼠标,C#,句柄,获取,int,hdc,public
来源: https://www.cnblogs.com/Jiangjhq6688/p/16179067.html