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

#308 – Checking to See Which Control Has Keyboard Focus

You can use the Keyboard.FocusedElement static property (in System.Windows.Input namespace) to determine which control currently has focus.

Here’s an example:

        private void DumpFocus()
        {
            IInputElement elem = Keyboard.FocusedElement;

            if (elem == null)
                Debug.WriteLine("Nobody has focus");
            else
            {
                FrameworkElement felem = elem as FrameworkElement;
                if (felem != null)
                {
                    string identifier = ((felem.Name != null) && (felem.Name.Length > 0)) ?
                        felem.Name :
                        felem.GetType().ToString();
                    Debug.WriteLine(string.Format("FrameworkElement - {0}", identifier));
                }
                else
                {
                    // Maybe a FrameworkContentElement has focus
                    FrameworkContentElement fcelem = elem as FrameworkContentElement;
                    if (fcelem != null)
                    {
                        string identifier = ((fcelem.Name != null) && (fcelem.Name.Length > 0)) ?
                            fcelem.Name :
                            fcelem.GetType().ToString();
                        Debug.WriteLine(string.Format("FrameworkContentElement - {0}", identifier));
                    }
                    else
                    {
                        Debug.WriteLine(string.Format("Element of type {0} has focus", elem.GetType().ToString()));
                    }
                }
            }
        }

#307 – Giving Focus to a Control When an Application Starts

A WPF application does not automatically gives keyboard focus to any single control when the application starts.  You can force a control to get focus at application startup by using the Keyboard.Focus static method (in the System.Windows.Input namespace).

Here’s an example that sets focus to one of the TextBox controls in the main window.

        public MainWindow()
        {
   	        this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

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

#306 – Keyboard Focus

In WPF, as in other Windows applications, a control or user interface element has focus if it can receive keyboard input.  Specifically, we say that the control has keyboard focus.

By default, when a WPF application start up, no control has focus.  You can give a control focus by pressing the TAB key–which cycles through all of the controls that are able to receive focus.  You can also give a control focus by clicking on the control.

Not all controls are able to receive focus.  In general, only controls that can accept user input can get focus.

Most controls will give some visual indication that the control currently has keyboard focus.  Many controls will display a dashed line around the control to indicate that it has focus.  The TextBox will display a light blue border to show that it has focus and also contain an editing carat.

#305 – Guidelines for Defining Access Keys

Microsoft defines the following guidelines for defining access keys, in the Windows User Experience Interaction Guidelines.

  • Use wider characters for the access key  (e.g. avoid ‘i’, ‘I’)
  • Use a distinctive consonant or vowel  (e.g. _Sort rather than So_rt)
  • Avoid using characters that make it hard to see the underline  (e.g. characters with descenders, like ‘y’)
  • Assign an access key to every menu item
  • For dynamically created menu items (e.g. list of recent files), use numeric access keys
  • Assign unique keys within a particular menu
  • First choice is to use first character of first or second word in label
  • Assign an access key to every control in a window that takes input, or to a nearby label
  • Assign unique keys within a particular window or dialog
  • Don’t assign access keys for OK and Cancel buttons
  • Don’t assign an access key to a control that has no associated caption or label

#304 – Defining an Access Key That Gives Focus to a Different Control

For controls that don’t have their own textual caption, it’s common to define an access key for a nearby label.  When that access key is activated, the control without the caption gets the focus.

In the example below, there is a TextBox where you can enter your name and the nearby Label “Enter Name”.  This screenshot was taken after the ALT key was pressed, so the ‘N’ in “Enter Name” is underlined, indicating that ‘N’ is the access key.  If the user presses ALT-N, the TextBox will get focus and they can then begin typing the name.

You can specify the control that should be the target of an access key by using the Target property on the control where you define the access key.

            <!-- Access key on Label gives focus to TextBox -->
            <Label Content="Enter _Name:" VerticalAlignment="Center" Target="txtName" />
            <TextBox Name="txtName" Width="150" Margin="10"/>
Follow

Get every new post delivered to your Inbox.

Join 373 other followers