#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.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #310 – Give a Control Logical Focus

  1. Eljay says:

    How does that differ from…
    txtFirst.Focus();

  2. Glenn says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: