#310 – Give a Control Logical Focus
May 31, 2011 3 Comments
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.
How does that differ from…
txtFirst.Focus();
Take a look at https://wpf.2000things.com/2011/06/01/311-giving-focus-to-a-control-part-ii/
That’s incorrect. FocusManager.SetFocusedElement does give keyboard focus, sometimes. See http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.setfocusedelement(v=vs.110).aspx: “and will attempt to give the element keyboard focus”. As far as I can tell, it’s impossible to reliably change the logical control of a focus scope without sometimes stealing keyboard focus too, which largely defeats the purpose of having them separate.