Skip to content

Commit

Permalink
Start and stop the mouse hook for the tray context menu
Browse files Browse the repository at this point in the history
  • Loading branch information
awaescher committed Dec 1, 2023
1 parent 14dfcac commit 79bdeb1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 12 deletions.
4 changes: 3 additions & 1 deletion StageManager/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@
IconSource="StageManager.ico"
MenuActivation="LeftOrRightClick">
<tb:TaskbarIcon.ContextMenu>
<ContextMenu>
<ContextMenu
Opened="ContextMenu_Opened"
Closed="ContextMenu_Closed">
<MenuItem
Header="Start with Windows"
IsCheckable="True"
Expand Down
49 changes: 38 additions & 11 deletions StageManager/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,12 @@ protected override void OnInitialized(EventArgs e)
_thisHandle = new System.Windows.Interop.WindowInteropHelper(this).Handle;
_lastWidth = Width;

_hook = new TaskPoolGlobalHook();

_hook.MousePressed += OnMousePressed;
_hook.MouseReleased += OnMouseReleased;
_hook.MouseMoved += _hook_MouseMoved;

Task.Run(_hook.Run);
StartHook();
}

protected override void OnClosed(EventArgs e)
{
_hook.MousePressed -= OnMousePressed;
_hook.MouseReleased -= OnMouseReleased;
_hook.MouseMoved -= _hook_MouseMoved;
_hook.Dispose();
StopHook();

trayIcon.Dispose();

Expand Down Expand Up @@ -318,6 +309,32 @@ private void ApplyWindowMode()
BeginAnimation(LeftProperty, animation);
}

private void StartHook()
{
_hook = new TaskPoolGlobalHook();

_hook.MousePressed += OnMousePressed;
_hook.MouseReleased += OnMouseReleased;
_hook.MouseMoved += _hook_MouseMoved;

Task.Run(_hook.Run);
}

private void StopHook()
{
_hook.MousePressed -= OnMousePressed;
_hook.MouseReleased -= OnMouseReleased;
_hook.MouseMoved -= _hook_MouseMoved;

try
{
_hook.Dispose();
}
catch (HookException)
{
}
}

private void _hook_MouseMoved(object? sender, MouseHookEventArgs e)
{
_mouse.X = e.Data.X;
Expand Down Expand Up @@ -378,6 +395,16 @@ private void MenuItem_Quit_Click(object sender, RoutedEventArgs e)
{
Close();
}

private void ContextMenu_Closed(object sender, RoutedEventArgs e)
{
StartHook();
}

private void ContextMenu_Opened(object sender, RoutedEventArgs e)
{
StopHook();
}
}

public enum WindowMode
Expand Down

0 comments on commit 79bdeb1

Please sign in to comment.