【WPF】取色器
- 序
- 实现
- Hook
- Screen Color
- layout
- .CS
- 预览
- 下载
序
取色器是一个非常实用的小工具,网上也很多可供下载使用。为什么已有却还是想要自己去实现一个呢?一方面是因为工具虽小但毕竟涉及到操作系统 API 的使用。另一方面想要在技术上精进一些。
实现
实现思路测试通过 Hook 鼠标左键单击,获取到鼠标位于屏幕坐标位置,再获取当前位置所渲染的颜色。
Hook
订阅鼠标左键点击事件,将鼠标坐标获取到当前程序。
using System.Runtime.InteropServices;
using System.Windows;namespace ColorExtractor
{public partial class GlobalMouseHook{private const int WH_MOUSE_LL = 14;private const int WM_LBUTTONDOWN = 0x0201;private const int WM_LBUTTONUP = 0x0202;public event EventHandler<Point> MouseReleased;private LowLevelMouseProc _proc;private IntPtr _hookID = IntPtr.Zero;public GlobalMouseHook(){_proc = HookCallback;}public void SetHook(){_hookID = SetWindowsHookEx(WH_MOUSE_LL, _proc, IntPtr.Zero, 0);}public void ReleaseHook(){UnhookWindowsHookEx(_hookID);}private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam){if (nCode >= 0){if (wParam == (IntPtr)WM_LBUTTONUP){MSLLHOOKSTRUCT hookStruct = Marshal.PtrToStructure<MSLLHOOKSTRUCT>(lParam);MouseReleased?.Invoke(this, new Point(hookStruct.pt.x, hookStruct.pt.y));}}return CallNextHookEx(_hookID, nCode, wParam, lParam);}private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);[DllImport("user32.dll", CharSet = CharSet