#310 – Give a Control Logical Focus

You can give a control the keyboard focus using the static Keyboard.Focus method.  If you want to instead give a control the logical focus, you can use the FocusManager.SetFocusedElement static method.  (In the System.Windows.Input namespace).

                // Give logical focus to txtFirst TextBox
                DependencyObject focusScope = FocusManager.GetFocusScope(txtFirst);
                FocusManager.SetFocusedElement(focusScope, txtFirst);

If you do this in an application with multiple windows and you set logical focus for a control in the inactive window, you’ll see that it does not get keyboard focus.  You can continue entering text in a control in the active window.  But when you switch back to the inactive window, you’ll see that the control does get keyboard focus.

Advertisement