0

I have a textBox which is being used for the Search engine inside my Form as parameter. The KeyDown event on the textBox calls a method on Enter. After that I need the focus to be placed on the same textbox. How can I place the focus on that textBox ?

the code:

private void txtName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSearch_Click(sender, e);
                txtName.Focusable = true;
                txtName.Focus();
            }
        }

It seems that is not working. So how can I make this work ?

  • You should use the [FocusManager.SetFocusedElement(...)](https://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.setfocusedelement%28v=vs.110%29.aspx) – Ron Beyer Apr 27 '18 at 14:18
  • These answers might help [Set focus on textbox in WPF](https://stackoverflow.com/questions/1345391/set-focus-on-textbox-in-wpf) – StevenGodin Apr 27 '18 at 14:29
  • Thank you, I don't know why focus() doesn't work. It seems that the focusmanager takes into consideration that I'm using a menu which has the textbox(txtName) inside of it... – Mihai Rădulescu Apr 28 '18 at 20:07
  • I've solved it using the following: private void txtName_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { IInputElement elem = e.NewFocus; DependencyObject d = elem as DependencyObject; if (FocusManager.GetIsFocusScope(d)) { d.SetValue(FocusManager.FocusedElementProperty, sender as DependencyObject); } } – Mihai Rădulescu Apr 30 '18 at 07:43

0 Answers0