C Global hotkey Settings and form hotkey Settings instance

  • 2020-11-20 06:12:47
  • OfStack

This article describes the example of C# global hotkey Settings and form hotkey Settings, to share for your reference. Specific implementation methods are as follows:

1. Form hotkeys

First, set the main form KeyPreview to true, which can be set directly in the properties,
Or set in form loading: this. KeyPreview = true;
Then add the Form KeyDown event as follows:

private void FrmMain_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Alt && e.Shift && e.Control && e.KeyCode == Keys.S)
    {
 MessageBox.Show(" I pressed the Control +Shift +Alt +S");
    }
}

2. Global hotkey setting

Define API function register hotkeys uninstall hotkeys

I have defined the AppHotKey class here, with all the code as follows:

public class AppHotKey
{
        [DllImport("kernel32.dll")]
        public static extern uint GetLastError();
        // If the function executes successfully, the return value is not 0 .
        // If the function fails, the return value is 0 . To get the extension error message, call GetLastError .
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,                // Handle to the window to define the hotkey
            int id,                     // Define hotkeys ID (Not with others ID Repeated)           
            KeyModifiers fsModifiers,   // Identifies whether the hotkey is being pressed Alt , Ctrl , Shift , Windows It doesn't take effect until you wait for the key
            Keys vk                     // Define the contents of the hotkey
            );         [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,                // Handle to the window to cancel the hotkey
            int id                      // You want to cancel hotkeys ID
            );         // Defines the name of the secondary key (converts a number to a character for memorization, or USES a numeric value instead of an enumeration)
        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }
        /// <summary>
        /// Registered hotkey
        /// </summary>
        /// <param name="hwnd"> Handle to the window </param>
        /// <param name="hotKey_id"> hotkey ID</param>
        /// <param name="keyModifiers"> The composite key </param>
        /// <param name="key"> hotkey </param>
        public static void RegKey(IntPtr hwnd, int hotKey_id, KeyModifiers keyModifiers, Keys key)
        {
            try
            {
                if (!RegisterHotKey(hwnd, hotKey_id, keyModifiers, key))
                {
                    if (Marshal.GetLastWin32Error() == 1409) { MessageBox.Show(" Hotkeys are occupied ! "); }
                    else
                    {
                        MessageBox.Show(" Failed to register hotkey! ");
                    }
                }
            }
            catch (Exception) { }
        }
        /// <summary>
        /// The cancellation of hot keys
        /// </summary>
        /// <param name="hwnd"> Handle to the window </param>
        /// <param name="hotKey_id"> hotkey ID</param>
        public static void UnRegKey(IntPtr hwnd, int hotKey_id)
        {
            // The cancellation Id Number is hotKey_id Hotkey Settings
            UnregisterHotKey(hwnd, hotKey_id);
        }
}

Overwrite the WndProc function of the form, register the hotkey when the window is created, and destroy the hotkey when the window is destroyed, the code is as follows:

private const int WM_HOTKEY = 0x312; // Window message - hotkey 
private const int WM_CREATE = 0x1; // Window message - create
private const int WM_DESTROY = 0x2; // Window message - The destruction
private const int Space = 0x3572; // hotkey ID
protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
    switch (m.Msg)
    {
 case WM_HOTKEY: // Window message - hotkey ID
     switch (m.WParam.ToInt32())
     {
  case Space: // hotkey ID
      MessageBox.Show(" I pressed the Control +Shift +Alt +S");
      break;
  default:
      break;
     }
     break;
 case WM_CREATE: // Window message - create
     AppHotKey.RegKey(Handle, Space, AppHotKey.KeyModifiers.Ctrl | AppHotKey.KeyModifiers.Shift | AppHotKey.KeyModifiers.Alt, Keys.S);
     break;
 case WM_DESTROY: // Window message - The destruction
     AppHotKey.UnRegKey(Handle, Space); // Destroy the hotkey
     break;
 default:
     break;
    }
}

Hopefully this article has helped you with your C# programming.


Related articles: