C#实现从鼠标光标位置获取屏幕颜色的技术问询
当然可以实现!这种取色器功能不管是做UI调试、色彩分析工具,还是日常的小需求都超实用。下面我给你分享几种常见的实现方式,先从最容易上手的Python方案说起:
Python 实现方案
这是跨平台的首选方案,依赖两个轻量库就能快速搞定:
- 首先安装依赖:
pyautogui(负责获取鼠标位置)和Pillow(负责捕获屏幕像素)
安装命令:pip install pyautogui pillow - 完整代码示例(带注释):
import pyautogui from PIL import ImageGrab def get_mouse_color(): # 获取当前鼠标的实时坐标 x, y = pyautogui.position() # 捕获整个屏幕的图像 screen_snapshot = ImageGrab.grab() # 获取指定坐标的RGB颜色值 rgb_color = screen_snapshot.getpixel((x, y)) # 转换为更常用的十六进制颜色格式 hex_color = '#{:02x}{:02x}{:02x}'.format(*rgb_color) return (x, y), rgb_color, hex_color # 运行测试:按Enter获取当前鼠标位置的颜色,Ctrl+C退出 print("移动鼠标到目标位置,按Enter获取颜色(按Ctrl+C退出)") while True: try: input() pos, rgb, hex_c = get_mouse_color() print(f"鼠标位置:({pos[0]}, {pos[1]})") print(f"RGB颜色:{rgb}") print(f"十六进制颜色:{hex_c}\n") except KeyboardInterrupt: print("\n程序已退出") break
- 关键说明:
pyautogui.position()会实时返回鼠标的全局坐标ImageGrab.grab()默认捕获整个屏幕,也可以传入区域参数只捕获指定范围- 新版本的pyautogui已经自动处理了高DPI屏幕的坐标偏移问题,不用额外配置
Windows C# 原生实现方案
如果是Windows平台的桌面应用,用C#原生API也能轻松实现:
- 代码示例:
using System; using System.Drawing; using System.Windows.Forms; class ColorPickerTool { static void Main() { Console.WriteLine("移动鼠标到目标位置,按Enter获取颜色(按Ctrl+C退出)"); while (true) { Console.ReadLine(); // 获取鼠标当前位置 Point mousePosition = Cursor.Position; // 创建1x1的位图来捕获单个像素 using (Bitmap pixelBitmap = new Bitmap(1, 1)) { using (Graphics g = Graphics.FromImage(pixelBitmap)) { // 从屏幕指定位置复制像素到位图 g.CopyFromScreen(mousePosition, new Point(0, 0), new Size(1, 1)); } // 获取位图中的颜色值 Color targetColor = pixelBitmap.GetPixel(0, 0); Console.WriteLine($"鼠标位置:({mousePosition.X}, {mousePosition.Y})"); Console.WriteLine($"RGB颜色:R={targetColor.R}, G={targetColor.G}, B={targetColor.B}"); Console.WriteLine($"十六进制颜色:#{targetColor.R:X2}{targetColor.G:X2}{targetColor.B:X2}\n"); } } } }
- 注意事项:
- 需要引用
System.Drawing和System.Windows.Forms程序集(在Visual Studio中右键项目→添加引用即可) - 若遇到高DPI屏幕坐标偏移,需在应用程序清单中设置
dpiAware为true来适配
- 需要引用
如果还有其他特定平台或语言的需求,随时说,我再给你细化方案!
内容的提问来源于stack exchange,提问作者SenaCarbtc
相关产品推荐
相关产品推荐

