14

可以使用以下事件,但是必须为每个元素附加它们:

GotKeyboardFocus, LostKeyboardFocus

.NET WPF 中是否有办法全局检测焦点元素是否更改?无需为所有可能的元素添加事件监听器?

4

4 回答 4

20

您可以在任何课程中这样做:

//In the constructor
EventManager.RegisterClassHandler(
        typeof(UIElement),
        Keyboard.PreviewGotKeyboardFocusEvent,
        (KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);

...

private void OnPreviewGotKeyboardFocus(object sender, 
                                       KeyboardFocusChangedEventArgs e)
{

     // Your code here

}
于 2013-02-21T21:36:04.757 回答
6

您可以挂钩到隧道预览事件:

<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">
....

这样,如上所示,当任何后代获得或失去键盘焦点时,将在所有后代之前通知窗口。

阅读内容以获取更多信息。

于 2012-04-24T14:35:37.700 回答
5

您可以将路由事件处理程序添加到主窗口并指定您对处理的事件感兴趣。

mainWindow.AddHandler(
    UIElement.GotKeyboardFocusEvent,
    OnElementGotKeyboardFocus,
    true
);
于 2012-04-24T14:32:52.380 回答
0

看看微软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;
    }
}

这也适用于多窗口应用程序。

于 2016-09-01T15:11:42.273 回答