Search code examples
wpftextboxsendkeys

Using Sendkes.Send function in WPF


I have a wpf application. In my TextBox, I want when user press "Enter" key, focus jumps to next tab index control, like pressing tab key, I use this code

if (e.Key == Key.Enter)
{
     SendKeys.Send("{TAB}");
}
if (e.Key == Key.Escape)
{
     SendKeys.Send("+{tab}");
}

but this doesn't work. could you please help me?


Solution

  • You need to use the TraversalRequest:

    if (e.Key == Key.Enter)
            {
                TraversalRequest tRequest = new TraversalRequest(FocusNavigationDirection.Next);               
                UIElement keyboardFocus = Keyboard.FocusedElement as UIElement;
    
                if (keyboardFocus != null)
                {
                    keyboardFocus.MoveFocus(tRequest);
                }
    
                e.Handled = true;
            }           
    

    The TraversalRequest takes the FocusNAvigationDirection as its parameter, determining the direction in which you want to navigate.

    Also, this is the MSDN on traversalRequest class.