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

Get every new post delivered to your Inbox.

Join 375 other followers