可以使用以下事件,但是必须为每个元素附加它们:
GotKeyboardFocus, LostKeyboardFocus
.NET WPF 中是否有办法全局检测焦点元素是否更改?无需为所有可能的元素添加事件监听器?
可以使用以下事件,但是必须为每个元素附加它们:
GotKeyboardFocus, LostKeyboardFocus
.NET WPF 中是否有办法全局检测焦点元素是否更改?无需为所有可能的元素添加事件监听器?
您可以在任何课程中这样做:
//In the constructor
EventManager.RegisterClassHandler(
typeof(UIElement),
Keyboard.PreviewGotKeyboardFocusEvent,
(KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);
...
private void OnPreviewGotKeyboardFocus(object sender,
KeyboardFocusChangedEventArgs e)
{
// Your code here
}
您可以挂钩到隧道预览事件:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525"
PreviewGotKeyboardFocus="Window_PreviewGotKeyboardFocus"
PreviewLostKeyboardFocus="Window_PreviewLostKeyboardFocus">
....
这样,如上所示,当任何后代获得或失去键盘焦点时,将在所有后代之前通知窗口。
阅读此内容以获取更多信息。
您可以将路由事件处理程序添加到主窗口并指定您对处理的事件感兴趣。
mainWindow.AddHandler(
UIElement.GotKeyboardFocusEvent,
OnElementGotKeyboardFocus,
true
);
看看微软CommandManager.RequerySuggested
在焦点改变时如何触发事件:他们订阅InputManager.PostProcessInput
事件。
简单的例子:
static KeyboardControl()
{
InputManager.Current.PostProcessInput += InputManager_PostProcessInput;
}
static void InputManager_PostProcessInput(object sender, ProcessInputEventArgs e)
{
if (e.StagingItem.Input.RoutedEvent == Keyboard.GotKeyboardFocusEvent ||
e.StagingItem.Input.RoutedEvent == Keyboard.LostKeyboardFocusEvent)
{
KeyboardFocusChangedEventArgs focusArgs = (KeyboardFocusChangedEventArgs)e.StagingItem.Input;
KeyboardControl.IsOpen = focusArgs.NewFocus is TextBoxBase;
}
}
这也适用于多窗口应用程序。