[C#] Focus to next control on Enter keypress in WPF

Updated on     Kisan Patel

Problem:

Focus to next control on Enter keypress in WPF
How to move focus to the next Control automatically?
Press Enter to move to next control [WPF] Enter Button To Move To Next Control [WPF]

Solution:

Just declare these event handlers in the OnStartup void of App.xaml

EventManager.RegisterClassHandler(typeof(TextBox), TextBox.KeyDownEvent, new KeyEventHandler(TextBox_KeyDown));
EventManager.RegisterClassHandler(typeof(CheckBox), CheckBox.KeyDownEvent, new KeyEventHandler(CheckBox_KeyDown));

Here are the rest of the methods needed to make it work application wide.

void TextBox_KeyDown(object sender, KeyEventArgs e)
{
	if (e.Key == Key.Enter & (sender as TextBox).AcceptsReturn == false) MoveToNextUIElement(e);
}

void CheckBox_KeyDown(object sender, KeyEventArgs e)
{
	MoveToNextUIElement(e);
	//Sucessfully moved on and marked key as handled.
	//Toggle check box since the key was handled and
	//the checkbox will never receive it.
	if (e.Handled == true)
	{
		CheckBox cb = (CheckBox)sender;
		cb.IsChecked = !cb.IsChecked;
	}

 }

void MoveToNextUIElement(KeyEventArgs e)
{
	// Creating a FocusNavigationDirection object and setting it to a
	// local field that contains the direction selected.
	FocusNavigationDirection focusDirection = FocusNavigationDirection.Next;

	// MoveFocus takes a TraveralReqest as its argument.
	TraversalRequest request = new TraversalRequest(focusDirection);

	// Gets the element with keyboard focus.
	UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

	// Change keyboard focus.
	if (elementWithFocus != null)
	{
		if (elementWithFocus.MoveFocus(request)) e.Handled = true;
	}
}


Source:
http://stackoverflow.com/questions/8203329/moving-to-next-control-on-enter-keypress-in-wpf


C# WPF