nikorio
nikorio

Reputation: 691

Using of left/right keyboard button

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();
       }
   }

Upvotes: 1

Views: 782

Answers (2)

Joshua Hysong
Joshua Hysong

Reputation: 1072

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.

Upvotes: 2

Lotte Lemmens
Lotte Lemmens

Reputation: 581

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

Upvotes: 1

Related Questions