using System; using System.Runtime.InteropServices; using Microsoft.UI.Xaml; namespace ClipForge { public class GlobalHotkeyService { [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); private const int HOTKEY_CLIP = 1; private const uint MOD_NOREPEAT = 0x4000; // don't fire on key repeat public event Action? ClipRequested; private IntPtr _hwnd; private uint _modifiers; private uint _vk; /// Register the clip hotkey. Use settings values (e.g. HotkeyModifiers, HotkeyVirtualKey). public void Initialize(IntPtr hwnd, uint modifiers, uint vk) { _hwnd = hwnd; _modifiers = modifiers; _vk = vk; TryRegister(); } /// Update the hotkey at runtime (e.g. after user remaps). Unregisters old and registers new. public bool UpdateHotkey(uint modifiers, uint vk) { UnregisterHotKey(_hwnd, HOTKEY_CLIP); _modifiers = modifiers; _vk = vk; return TryRegister(); } private bool TryRegister() { uint mod = _modifiers | MOD_NOREPEAT; return RegisterHotKey(_hwnd, HOTKEY_CLIP, mod, _vk); } public void ProcessHotkey(int id) { if (id == HOTKEY_CLIP) ClipRequested?.Invoke(); } public void Cleanup() { UnregisterHotKey(_hwnd, HOTKEY_CLIP); } } }