Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get currently focused element/control in a WPF window

Tags:

.net

focus

wpf

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

like image 890
honzajscz Avatar asked Oct 15 '13 22:10

honzajscz


1 Answers

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;
like image 72
sa_ddam213 Avatar answered Sep 27 '22 02:09

sa_ddam213