#311 – Giving Focus to a Control, Part II

You can give focus to a specific control at run-time using the Keyboard.Focus static method.  You can also give focus to any control that inherits from UIElement using the control’s Focus method.

		public MainWindow()
		{
			this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);

		}

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // On startup, set focus to first TextBox in window
            txtFirst.Focus();
        }

The difference between these two methods is:

  • Keyboard.Focus just sets keyboard focus
  • UIElement.Focus tries to set keyboard focus.  If the control fails to get keyboard focus, the method sets logical focus to the control
Advertisements

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

#309 – Keyboard Focus vs. Logical Focus

In WPF, there are two types of focus–keyboard focus and logical focus.

If an element has keyboard focus, it is the element that can currently receive input from the keyboard.  Only a single element in an entire application can have keyboard at any given time.

An element has logical focus if it is the element within a focus scope that has focus.  The idea is that WPF keeps track of one or more groups of controls, each of which makes up a focus scope.  Within each focus scope, a single control can have logical focus.  This allows WPF to remember the control that last had focus in a group of controls and give the keyboard focus back to the proper control when a group of controls becomes active again.

An element that has keyboard focus always has logical focus.  An element that has logical focus may not have keyboard focus.