ClipboardHook.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Windows.Interop;
  3. using HandyControl.Tools.Interop;
  4. namespace HandyControl.Tools;
  5. public class ClipboardHook
  6. {
  7. public static event Action ContentChanged;
  8. private static HwndSource HWndSource;
  9. private static IntPtr HookId = IntPtr.Zero;
  10. private static int Count;
  11. public static void Start()
  12. {
  13. if (HookId == IntPtr.Zero)
  14. {
  15. HookId = WindowHelper.CreateHandle();
  16. HWndSource = HwndSource.FromHwnd(HookId);
  17. if (HWndSource != null)
  18. {
  19. HWndSource.AddHook(WinProc);
  20. InteropMethods.AddClipboardFormatListener(HookId);
  21. }
  22. }
  23. if (HookId != IntPtr.Zero)
  24. {
  25. Count++;
  26. }
  27. }
  28. public static void Stop()
  29. {
  30. Count--;
  31. if (Count < 1)
  32. {
  33. HWndSource.RemoveHook(WinProc);
  34. InteropMethods.RemoveClipboardFormatListener(HookId);
  35. HookId = IntPtr.Zero;
  36. }
  37. }
  38. private static IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
  39. {
  40. if (msg == InteropValues.WM_CLIPBOARDUPDATE)
  41. {
  42. ContentChanged?.Invoke();
  43. }
  44. return IntPtr.Zero;
  45. }
  46. }