How can I acquire the currently focused element/control in WPF from code that is part of neither a window nor an user control?
It depends on the type of focus you are after, Logical
or Keyboard
.
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;