I was asked by our user interaction designer to make Enter key presses mimic a Tab key press by moving focus to the next control where TabStop=true. Sounds simple enough. But after several fruitless searches on Google, I thought I would have to resort to using unmanaged code. Luckly, I finally found a blog post with the answer that I was looking. Well, the post itself didn’t solve my problem, but the comments pointed me in the right direction.

The initial suggestion to override the form’s OnKeyUp event doesn’t apply to my case because my text fields were in a panel. ProcessKeyTab is a protected method that can only be called when you extend a control that is derived from ContainerControl, such as Form or Panel. Since I didn’t extend the Panel I was using, I couldn’t call ProcessKeyTab.

After reading the comments, I found that the answer lies in using the static SendKeys.Send method. In each TextBox that you want to treat Enter as Tab, simply handle the KeyPress event and call SendKeys.Send(”{TAB}”) if the key pressed is an Enter key.

[csharp]
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ‘\r’)
{
e.Handled = true;
System.Windows.Forms.SendKeys.Send(”{TAB}”);
}
}
[/csharp]

Initially, I handled the KeyUp event, as suggested in the blog post mentioned above; however, I had the problem of the system bell getting dingged with every Enter key press. I thought setting e.Handled = true would do it, but it didn’t. I then changed the code to do handle the KeyDown event (because the method signature was the same for both the KeyDown and KeyUp events), but the bell was still dinging. Lastly, I tried the KeyPress and it worked.

One other thing that I did, since I had several text boxes on my form, was to create a custom control that extended TextBox. This EnterAsTabTextBox control simply over-rode the OnKeyPress method and the same code as shown above. I also added a public bool EnterAsTab property that would allow users to control whether or not an Enter key press would mimic a Tab key press. Once the control was complete, I simply went into the .Designer.cs of my view and changed the references of my text fields from TextBox to EnterAsTabTextBox.

Lastly, if you want to move focus in the reverse direction, similiar to pressing SHIFT+TAB:

[csharp]
System.Windows.Forms.SendKeys.Send(”+{TAB}”);
[/csharp]

For more information on SendKeys.Send, visit the MSDN site.