是否可以全局检测键盘焦点事件?

时间:2012-04-24 14:07:36

标签: wpf

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

GotKeyboardFocus,LostKeyboardFocus

.NET WPF中是否有办法全局检测焦点元素是否发生了变化?无需为所有可能的元素添加事件侦听器?

4 个答案:

答案 0 :(得分:14)

您可以在任何类中执行此操作:

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

...

private void OnPreviewGotKeyboardFocus(object sender, 
                                       KeyboardFocusChangedEventArgs e)
{

     // Your code here

}

答案 1 :(得分:5)

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

mainWindow.AddHandler(
    UIElement.GotKeyboardFocusEvent,
    OnElementGotKeyboardFocus,
    true
);

答案 2 :(得分:3)

您可以挂钩tunneling预览事件:

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

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

阅读this了解详情。

答案 3 :(得分:0)

了解Microsoft在焦点更改时如何触发CommandManager.RequerySuggested事件:他们订阅InputManager.PostProcessInput事件。

ReferenceSource

简单示例:

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

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