2010-01-12

Moving the focus to the next element with the Enter key

In Windows applications where users have to input big amounts of data, some people find it better to be able to move to the next control in the Form with the Enter key (as well as the Tab key). To accomplish that, you could always handle the KeyDown event on each control, and move the focus to the next control in the list. While this is effective, it'll get boring if your form has a lot of controls.

The other way around is to handle the Form's KeyDown event directly, and move to the next UIElement in the list. Something like this (the example is done with a WPF Window object, not a WinForm, but the idea is the same):

  1: private void Window_KeyDown(object sender, KeyEventArgs e)
  2: {
  3:     //Enable this code if you don't want to use the Tab key anymore
  4:     /*if (e.Key == Key.Tab)
  5:     {
  6:         e.Handled = true;
  7:         return;
  8:     }*/
  9: 
 10:     if (e.Key == Key.Enter)
 11:     {
 12:         var tRequest = new TraversalRequest(FocusNavigationDirection.Next);
 13:         var keyboardFocus = Keyboard.FocusedElement as UIElement;
 14: 
 15:         if (keyboardFocus != null)
 16:         {
 17:             keyboardFocus.MoveFocus(tRequest);
 18:         }
 19: 
 20:         e.Handled = true;
 21:     }
 22: }

As Ben Ronco – MSFT recommended it in the forumk thread I started asking this: "be careful when using a key like Enter to control navigation if the elements in your application include controls that also consume Enter keystrokes".

No hay comentarios:

Publicar un comentario

Your tips and thoughts are always welcome, and they provide good motivation: