How do you check if a shortcut was pressed using c#?

Morgenstern 40 Reputation points
2023-03-28T01:46:31.9966667+00:00

I want to make an app hide itself if a shortcut was pressed (ex: Alt + Shift + Z), and then show itself if a different shortcut was pressed. However, I do not know how to figure out if multiple keys were pressed. Thanks in advance.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,937 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,491 Reputation points Microsoft Vendor
    2023-03-28T06:07:00.35+00:00

    @Morgenstern, Welcome to Microsoft Q&A, I recommend that you could try to use windows api RegisterHotKey function to register the hot key and then use the HotKeyPressed event to check if the combinations keys are pressed.

    Here is a code example in windows form app:

    using System;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Windows.Forms;
    
    
    
    
    
    
    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            
            private void Form1_Load(object sender, EventArgs e)
            {
                HotKeyManager.RegisterHotKey(Keys.Z, KeyModifiers.Alt|KeyModifiers.Shift);
                HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
            }
             void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
            {
                this.Invoke(new MethodInvoker(this.Hide));
            }
    
        }
    
        public static class HotKeyManager
        {
            public static event EventHandler<HotKeyEventArgs> HotKeyPressed;
    
            public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
            {
                _windowReadyEvent.WaitOne();
                int id = System.Threading.Interlocked.Increment(ref _id);
                _wnd.Invoke(new RegisterHotKeyDelegate(RegisterHotKeyInternal), _hwnd, id, (uint)modifiers, (uint)key);
                return id;
            }
    
            public static void UnregisterHotKey(int id)
            {
                _wnd.Invoke(new UnRegisterHotKeyDelegate(UnRegisterHotKeyInternal), _hwnd, id);
            }
    
            delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key);
            delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id);
    
            private static void RegisterHotKeyInternal(IntPtr hwnd, int id, uint modifiers, uint key)
            {
                RegisterHotKey(hwnd, id, modifiers, key);
            }
    
            private static void UnRegisterHotKeyInternal(IntPtr hwnd, int id)
            {
                UnregisterHotKey(_hwnd, id);
            }
    
            private static void OnHotKeyPressed(HotKeyEventArgs e)
            {
                if (HotKeyManager.HotKeyPressed != null)
                {
                    HotKeyManager.HotKeyPressed(null, e);
                }
            }
    
            private static volatile MessageWindow _wnd;
            private static volatile IntPtr _hwnd;
            private static ManualResetEvent _windowReadyEvent = new ManualResetEvent(false);
            static HotKeyManager()
            {
                Thread messageLoop = new Thread(delegate ()
                {
                    Application.Run(new MessageWindow());
                });
                messageLoop.Name = "MessageLoopThread";
                messageLoop.IsBackground = true;
                messageLoop.Start();
            }
    
            private class MessageWindow : Form
            {
                public MessageWindow()
                {
                    _wnd = this;
                    _hwnd = this.Handle;
                    _windowReadyEvent.Set();
                }
    
                protected override void WndProc(ref Message m)
                {
                    if (m.Msg == WM_HOTKEY)
                    {
                        HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);
                        HotKeyManager.OnHotKeyPressed(e);
                    }
    
                    base.WndProc(ref m);
                }
    
                protected override void SetVisibleCore(bool value)
                {
                    // Ensure the window never becomes visible
                    base.SetVisibleCore(false);
                }
    
                private const int WM_HOTKEY = 0x312;
            }
    
            [DllImport("user32", SetLastError = true)]
            private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
    
            [DllImport("user32", SetLastError = true)]
            private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    
            private static int _id = 0;
        }
    
    
        public class HotKeyEventArgs : EventArgs
        {
            public readonly Keys Key;
            public readonly KeyModifiers Modifiers;
    
            public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
            {
                this.Key = key;
                this.Modifiers = modifiers;
            }
    
            public HotKeyEventArgs(IntPtr hotKeyParam)
            {
                uint param = (uint)hotKeyParam.ToInt64();
                Key = (Keys)((param & 0xffff0000) >> 16);
                Modifiers = (KeyModifiers)(param & 0x0000ffff);
            }
        }
    
        [Flags]
        public enum KeyModifiers
        {
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8,
            NoRepeat = 0x4000
        }
    
    

    Based on my test, it will hide the current form when you press Alt + Shift + Z.

    Hope my solution could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.