Can {Enter} tab to the next control?

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

Is there an easy way to make the {Enter} key take the cursor to the next
control without using a KeyDown event on each control?
 
I haven't tried this, however, you might try wiring up a message filter
(IMessageFilter) and add it to the mix using the
Application.AddMessageFilter() method. You could check for an Enter key
press, eat that message, and then throw a Tab key press in it's place. This
may have consequences such as not being able to break to a new line in a
multiline TextBox, and maybe some other issues as well. But this should
place your Enter key handling at the application level.
 
Oh, some other side effects could be the user not being able to select the
default accept button on a form or not being able to simulate a button press
when it has focus. So a solution at the application level may be too high up
to be done realistically. Unless, of course, you handle all the necessary
cases by checking where the message is directed and allowing certain Enters
to get through. If its not obvious, I'm really just thinking out loud on
this one.
 
You could do it on a key event for the form, if you set the form.KeyPreview
to true. Or you could override the ProcessCmdKey() for the form. However,
it's not hard to have each control handle the KeyDown. You could call a
method in the Load() event of your form to attach them all. Something like:

void AttachKeyDownToControls(ControlCollection ccoll)
{
foreach ( Control c in ccoll.Controls )
{
if ( c.Controls != null )
{
AttachKeyDownToControls( c.Controls )
}
else
{
c.KeyDown += <whatever it is you do when you attach a KeyDown
event>;
}
}
}

This sort of thing works well if you only want to attach them to a certain
type of control. In the "else", you might really say

else if ( c is TextBoxBase && !c.Multiline )
// not sure if TextBoxBase really has multiline property but you get the
idea)
c.KeyDown += ...
 
Back
Top