antfu / live-draw

A tool allows you to draw on screen real-time.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Global hotkeys (With Code)

Sleepylux opened this issue · comments

commented

Clear and concise description of the problem

A global hotkey would be useful for enabling/disabling the app whether its in focus or not
I have already wrote the code for this, just remove.txt and it will work as of 08/08/2023 source code

Suggested solution

Entire working MainWindow.xaml.cs file: MainWindow.xaml.cs.txt

Alternative

Just the changed code:

        // imports
        [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 IntPtr windowHandle;
        private HwndSource source;


        // under lifetime
        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);

            SetupHotkeys();
        }

        private void Exit(object sender, EventArgs e)
        {
            if (IsUnsaved())
                QuickSave("ExitingAutoSave_");

            source.RemoveHook(HwndHook);
            UnregisterHotKey(windowHandle, 1200);

            Application.Current.Shutdown(0);
        }


        // Under shortcuts
        private void SetupHotkeys()
        {

            windowHandle = new WindowInteropHelper(this).Handle;
            source = HwndSource.FromHwnd(windowHandle);
            source.AddHook(HwndHook);

            RegisterHotKey(windowHandle, 2300, 0x0001 | 0x0004, 0x52); //ALT + SHIFT + R - Enable/disable hotkey when not focused
        }

        private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int WM_HOTKEY = 0x0312;
            switch (msg)
            {
                case WM_HOTKEY:
                    switch (wParam.ToInt32())
                    {
                        case 2300:
                            SetEnable(!_enable);
                            handled = true;
                            break;
                    }
                    break;
            }
            return IntPtr.Zero;
        }

Validations

+1. please add this as it would make workflow so much better