序
取色器是一个非常实用的小工具,网上也很多可供下载使用。为什么已有却还是想要自己去实现一个呢?一方面是因为工具虽小但毕竟涉及到操作系统 API 的使用。另一方面想要在技术上精进一些。
实现
实现思路测试通过 Hook 鼠标左键单击,获取到鼠标位于屏幕坐标位置,再获取当前位置所渲染的颜色。文章来源:https://www.toymoban.com/news/detail-857989.html
Hook
订阅鼠标左键点击事件,将鼠标坐标获取到当前程序。文章来源地址https://www.toymoban.com/news/detail-857989.html
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
到了这里,关于【WPF】取色器-Color Extractor的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!