Get currently focused element/control in a WPF window

.NetWpfFocus

.Net Problem Overview


How can I acquire the currently focused element/control in WPF from code that is part of neither a window nor an user control?

.Net Solutions


Solution 1 - .Net

It depends on the type of focus you are after, Logical or Keyboard.

  • Keyboard focus refers to the element that currently receives keyboard input. Only one element in the entire desktop can have keyboard focus.
  • Logical focus refers to the element in a focus scope that would receive the keyboard input, if the focus scope was active.

Usually the Logical Focus is the element which last received keyboard focus on that focus scope. A focus scope might be an app, a form, a top level window, a tab and so forth. In other words, logical focus is how a form or window remembers which control last had the keyboard focus.

FocusManager gets the element with logical focus within the specified focus scope, in this case the Window (this):

IInputElement focusedControl = FocusManager.GetFocusedElement(this);

Keyboard will return the element with the current keyboard input focus:

IInputElement focusedControl =  Keyboard.FocusedElement;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhonzajsczView Question on Stackoverflow
Solution 1 - .Netsa_ddam213View Answer on Stackoverflow