#1,067 – Experimenting with Keyboard Focus

A control has keyboard focus if it can accept input from the keyboard.  The sample code below is a working app that lets us experiment with keyboard focus by setting a Label to indicate which control has focus.

XAML includes some controls and defines a GotKeyboardFocus for the top-level Window.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Keyboard Focus" Width="320" Height="190"
        GotKeyboardFocus="Window_GotKeyboardFocus">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <StackPanel Orientation="Horizontal">
            <StackPanel Background="AliceBlue" Margin="5">
                <TextBox Name="txtLeft" Margin="5" Width="80"/>
                <Button Name="btnClickMe" Content="Click Me" Margin="5"/>
            </StackPanel>

            <StackPanel Background="PaleGoldenrod" Margin="5">
                <Label Content="I'm a Label"/>
                <TextBox Name="txtRight" Margin="5" Width="80"/>
                <CheckBox Name="chkCheckMe" Margin="5" Content="Check Me"/>
            </StackPanel>
        </StackPanel>

        <Label Grid.Row="1" Margin="5" Content="{Binding WhoHasFocus}"/>
    </Grid>
</Window>

Code-behind uses this code to set property indicating who has focus.

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
//using System.Windows.Media;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        private string whoHasFocus;
        public string WhoHasFocus
        {
            get { return whoHasFocus; }
            set {
                if (value != whoHasFocus)
                {
                    whoHasFocus = value;
                    RaisePropertyChanged("WhoHasFocus");
                }
            }
        }

        private void Window_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            CheckKeyboardFocus();
        }

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

            if (elem == null)
                WhoHasFocus = "NO FOCUS";
            else
            {
                FrameworkElement felem = elem as FrameworkElement;
                if (felem != null)
                {
                    string identifier = ((felem.Name != null) && (felem.Name.Length > 0)) ?
                        felem.Name :
                        felem.GetType().ToString();
                    WhoHasFocus = 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();
                        WhoHasFocus = string.Format("FrameworkContentElement [{0}]", identifier);
                    }
                    else
                    {
                        WhoHasFocus = string.Format("Element of type [{0}] has focus", elem.GetType().ToString());
                    }
                }
            }
        }
    }
}

1067-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,067 – Experimenting with Keyboard Focus

  1. Pingback: Dew Drop – May 7, 2014 (#1771) | Morning Dew

Leave a comment