views:

446

answers:

3

Hi i have a C# winform application with a particular form populated with a number of textboxes. I would like to make it so that by pressing the right arrow key this mimicks the same behaivour as pressing the tab key. Im not really sure how to do this.

I dont want to change the behaivour of the tab key at all, just get the right arrow key to do the same thing whilst on that form.

Can anyone offer any suggestions?

A: 

I think this will accomplish what you're asking:

private void form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Right)
    {
        Control activeControl = form1.ActiveControl;
        // may need to check for null activeControl
        form1.SelectNextControl(activeControl, true, true, true, true);
    }
}
Jamie Ide
A: 

You can use the KeyDown event on the form to trap the key stroke then perform whatever action you want. For example:

 private void MyForm_KeyDown(object sender, KeyEventArgs e)
 {
     if(e.KeyCode == Keys.Right)
     {
         this.SelectNextControl(....);
         e.Handled = true;
     }
 }

Don't forget to set the KeyPreview property on the form to True.

Sailing Judo
I would override the method instead of using the event. Also, I wouldn't do it on KeyDown you should really track between key down and up to make sure that you have a relevant full key press.
Brian ONeil
+1  A: 

You should override the OnKeyUp method in your form to do this...

protected override void OnKeyUp(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Right)
    {
       Control activeControl = this.ActiveControl;

       if(activeControl == null)
       {
            activeControl = this;
       }

       this.SelectNextControl(activeControl, true, true, true, true);
       e.Handled = true;
    }

    base.OnKeyUp(e);
}
Brian ONeil
Hi Brian, this seems to work ok but it only iterates through the controls on the container on which it resides - i.e. - the groupbox for example. so if i have 3 groupboxes with controls it wont jump over to the next one like the tab key will
I will update it to use SelectNext which I think does work recursively on containers.
Brian ONeil