#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()));
                    }
                }
            }
        }

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.

One Response to #308 – Checking to See Which Control Has Keyboard Focus

  1. Pingback: #1,067 – Experimenting with Keyboard Focus | 2,000 Things You Should Know About WPF

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: