1

I'm trying to call function with left and right buttons on keyboard, but not sure how to do it proper way.

In result of this attempt, pressing on left/right keyboard keys just switches between GUI elements usual way, and does not works for given functions. Not sure what is wrong here:

   private void Form1_KeyDown(object sender, KeyEventArgs e)
   {
       if (e.KeyCode == Keys.Right)
       {
          func1();
       }
       else if (e.KeyCode == Keys.Left)
       {
          func2();
       }
   }
nikorio
  • 671
  • 4
  • 16
  • 28
  • 2
    Have you enabled KeyPreview on your form? – Equalsk Apr 06 '17 at 12:11
  • 2
    I guess that's because you not handling event. Does the breakpoint hits while debugging? I think [keyprieview property](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview(v=vs.110).aspx) is what you looking for. – Renatas M. Apr 06 '17 at 12:11

2 Answers2

2

An alternative to enabling keypreview as mentioned in some comments would be to override the ProcessCmdKey Method.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    if (keyData == Keys.Right)
    {
      func1();
      return true;
    }
    else if (keyData == Keys.Left)
    {
      func2();
      return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

Please see this MSDN article for more information.

Joshua Hysong
  • 1,062
  • 1
  • 18
  • 31
  • This seems to be the correct answer. Setting `KeyPreview` to `true` is not always enough, the `KeyDown` handler of the `Form` still won't be called if e.g. a `Button` has the focus. `ProcessCmdKey` always gets called. – René Vogt Apr 06 '17 at 12:28
1

The code you have works correctly, you're just not allowed to press anything beforehand. I think you're looking for a general keydown as shown here

Community
  • 1
  • 1
Lotte Lemmens
  • 551
  • 5
  • 11