7
Answers

Navigate a keypad in winform using arrow keys

Stefan Cazacu

Stefan Cazacu

11y
1.9k
1
I'm currently working on a personal project and i have a bit of an issue. In the keypad display i ma unable to navigate up and down. Pressing the arrow keys only follows the button tabindex rather than the direction of the arrow key. For example: if i press the down arrow, instead of changing focus to button4, the focus moves to button2.
Although i have come up with some code that works, it does introduce a new problem. The OK button is initially hidden (until there have been 4 key presses), however in my code not only is the focus changed to it, it is also accessible through the keyboard. My question is: Is there a more elegant or efficient way of manipulating which button is focused?
Thank you.
(If it is of any help, i'm using visual studio 2008, C#, .NET3.5)

So far i have come up with this code:

private void frm_Login_KeyDown(object sender, KeyEventArgs e)
        {
           Control[] MyButtons = new Control[]{b1,b2,b3,b4,b5,b6,b7,b8,b9,btn_OK,b0,btn_Cancel}; 
switch (e.KeyValue)
{
   case 13: //return
         { e.Handled = false; break; }
   case 39:  //Right
          {
             if (IndexofFocussedButton < 11) { IndexofFocussedButton++; }
             else { IndexofFocussedButton = 0; }
             break;
           }
    case 38:  //Up
           {
               if (IndexofFocussedButton > 2) { IndexofFocussedButton-=3; }
               else { IndexofFocussedButton +=9; }
               break;
            }
    case 37: //Left
            {
               if (IndexofFocussedButton != 0) { IndexofFocussedButton--; }
               else { IndexofFocussedButton=11; }
            }
            break;
     case 40: //Down
            {
                if (IndexofFocussedButton < 9) { IndexofFocussedButton +=3; }
                else { IndexofFocussedButton-=9; }
                break;
             }


}


 if (e.KeyValue != 13)
{
    e.Handled = true;                 //Don't pass on the keystroke
    MyButtons[IndexofFocussedButton].Focus(); // Set the focus to the selected control
      Application.DoEvents();
}


Answers (7)