Search code examples
c#global-hotkey

How to define hot keys using if-else?


I want to perform two methods for different pressing of hot keys, checking in if-else what key was pressed

How to do this with this example?

I use so:

private static void Main()
{
  HotKeyManager.RegisterHotKey(key: Keys.G, modifiers: HotKeyEventArgs.KeyModifiers.Alt);
  HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
  Console.ReadLine();
}
private static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
{
  Console.WriteLine("Example HotKeys Activate");
}

How do I perform two different events with different HotKeys?


Solution

  • You need to register all your hotkey and then can use the Key and Modifiers properties of the HotKeyEventArgs:

    private static void Main()
    {
        HotKeyManager.RegisterHotKey(key: Keys.G, modifiers: HotKeyEventArgs.KeyModifiers.Alt);
        HotKeyManager.RegisterHotKey(key: Keys.P, modifiers: HotKeyEventArgs.KeyModifiers.Alt);
        HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
        Console.ReadLine();
    }
    private static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
    {
        if (e.Key == Keys.G && e.Modifiers == HotKeyEventArgs.KeyModifiers.Alt)
           OnPressedAltG();
        else if (e.Key == Keys.P && e.Modifiers == HotKeyEventArgs.KeyModifiers.Alt)
           OnPressedAltP();
    }
    
    private static void OnPressedAltG()
    {
        Console.WriteLine("Alt+G was pressed.");
    }
    private static void OnPressedAltP()
    {
        Console.WriteLine("Alt+P was pressed.");
    }