MouseHookThread.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using GeekDesk.Control.UserControls.Config;
  2. using GeekDesk.Control.Windows;
  3. using GeekDesk.Util;
  4. using GeekDesk.ViewModel;
  5. using Gma.System.MouseKeyHook;
  6. using System;
  7. using System.Drawing;
  8. using System.Threading;
  9. using System.Windows;
  10. using System.Windows.Threading;
  11. namespace GeekDesk.MyThread
  12. {
  13. public class MouseHookThread
  14. {
  15. private static readonly AppConfig appConfig = MainWindow.appData.AppConfig;
  16. public static Dispatcher dispatcher;
  17. private static UserActivityHook hook;
  18. public static void Hook()
  19. {
  20. //使用dispatcher来单独监听UI线程 防止程序卡顿
  21. dispatcher = DispatcherBuild.Build();
  22. dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  23. {
  24. hook = new UserActivityHook();
  25. if (appConfig.MouseMiddleShow)
  26. {
  27. hook.OnMouseWheelUp += OnMouseWheelUp;
  28. }
  29. hook.Start(true, false);
  30. }));
  31. }
  32. private static void OnMouseLeftDown(object sender, System.Windows.Forms.MouseEventArgs e)
  33. {
  34. }
  35. private static void OnMouseLeftUp(object sender, System.Windows.Forms.MouseEventArgs e)
  36. {
  37. }
  38. private static void OnMouseWheelUp(object sender, System.Windows.Forms.MouseEventArgs e)
  39. {
  40. MouseWheelShowApp(sender, e);
  41. }
  42. /// <summary>
  43. /// 鼠标中键呼出
  44. /// </summary>
  45. /// <param name="sender"></param>
  46. /// <param name="e"></param>
  47. private static void MouseWheelShowApp(object sender, System.Windows.Forms.MouseEventArgs e)
  48. {
  49. //中键打开App
  50. if (appConfig.MouseMiddleShow && MotionControl.hotkeyFinished)
  51. {
  52. App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
  53. {
  54. if (MainWindow.mainWindow.Visibility == Visibility.Collapsed || MainWindow.mainWindow.Opacity == 0)
  55. {
  56. MainWindow.ShowApp();
  57. }
  58. else
  59. {
  60. MainWindow.HideApp();
  61. }
  62. }));
  63. }
  64. }
  65. public static void Dispose()
  66. {
  67. try
  68. {
  69. if (hook != null)
  70. {
  71. if (hook.MouseWheelUpEnable())
  72. {
  73. hook.OnMouseWheelUp -= OnMouseWheelUp;
  74. }
  75. if (hook.MouseLeftDownEnable())
  76. {
  77. hook.OnMouseLeftDown -= OnMouseLeftDown;
  78. }
  79. if (hook.MouseLeftUpEnable())
  80. {
  81. hook.OnMouseLeftUp -= OnMouseLeftUp;
  82. }
  83. hook.Stop();
  84. dispatcher.InvokeShutdown();
  85. hook = null;
  86. dispatcher = null;
  87. }
  88. }
  89. catch (Exception ex)
  90. {
  91. LogUtil.WriteErrorLog(ex, "关闭hook出错");
  92. }
  93. }
  94. }
  95. }