Search code examples
.netwpffocus

Get currently focused element/control in a WPF window


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


Solution

  • 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;