none
C# Detect Key Combination Pressed

    Question

  • Hi,

       How can I detect on my Form if the following key combination is pressed in sequence.

    Hold ALT then 'P' then 'A' then 'U' then 'L'

    Thanks

    Paul.

    Wednesday, November 24, 2010 7:48 PM

Answers

  • Hi Paul,

    Here's an example how to do it.

    private StringBuilder _pressedKeys = new StringBuilder();
    
    protected override void OnKeyDown(KeyEventArgs e)
    {
     if (ModifierKeys == Keys.Alt)
     {
      var letter = (char)e.KeyValue;
    
      if (!char.IsLetterOrDigit(letter))
      {
       return;
      }
    
      _pressedKeys.Append(letter);
    
      if (_pressedKeys.ToString().ToLower() == "myword")
      {
       MessageBox.Show("It works!");
       _pressedKeys.Clear();
      }
     }
     else
     {
      _pressedKeys.Clear();
     }
    
     base.OnKeyDown(e);
    }
    

    Regards,
    Danijel

    Blog, Twitter
    • Marked as answer by pr_wainwright Thursday, November 25, 2010 7:43 AM
    Wednesday, November 24, 2010 8:45 PM