Search code examples
c#winformsuser-interfacekeyboardkeycode

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

Solution

  • 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.