.net 在 WPF 窗口中获取当前聚焦的元素/控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19392036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get currently focused element/control in a WPF window
提问by Honzajscz
How can I acquire the currently focused element/control in WPF from code that is part of neither a window nor an user control?
如何从既不属于窗口也不属于用户控件的代码获取 WPF 中当前聚焦的元素/控件?
回答by sa_ddam213
It depends on the type of focus you are after, Logicalor Keyboard.
这取决于您所追求的焦点类型,Logical或者Keyboard。
- Keyboard focusrefers to the element that currentlyreceives keyboard input. Only one element in the entire desktop can have keyboard focus.
- Logical focusrefers to the element in a focus scope that wouldreceive the keyboard input, ifthe 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.
通常逻辑焦点是最后在该焦点范围上接收到键盘焦点的元素。焦点范围可能是应用程序、表单、顶级窗口、选项卡等。换句话说,逻辑焦点是窗体或窗口如何记住最后获得键盘焦点的控件。
FocusManagergets the element with logical focus within the specified focus scope, in this case the Window (this):
FocusManager获取指定焦点范围内具有逻辑焦点的元素,在本例中为 Window ( this):
IInputElement focusedControl = FocusManager.GetFocusedElement(this);
Keyboardwill return the element with the current keyboard input focus:
Keyboard将返回具有当前键盘输入焦点的元素:
IInputElement focusedControl = Keyboard.FocusedElement;

