[按下Ctrl +空格时不触发对焦点元素的点击

问题描述 投票:0回答:1

在我的WPF应用程序中,按Ctrl + Space时会出现一个“全局”搜索框。按下Command + Space时,其行为类似于Mac OS中的Spotlight。

MainWindow.xaml.cs

public partial class MainWindow : Window
{
  public static RoutedCommand OpenSpotlight { get; set; } = new RoutedCommand();

  public MainWindow()
  {
    OpenSpotlight.InputGestures.Add(new KeyGesture(Key.Space, ModifierKeys.Control));
  }

  private void OpenSpotlight_Execute(object sender, ExecutedRoutedEventArgs e)
  {
    // Code which opens the search box ...
  }
}

MainWindow.xaml

<Window.CommandBindings>
  <CommandBinding Command="{x:Static local:MainWindow.OpenSpotlight}" Executed="OpenSpotlight_Execute"/>
</Window.CommandBindings>

工作正常,但有一个问题:当任何按钮都被聚焦时,按Ctrl + Space会触发该按钮被单击,因为正在按下Space键。

有什么办法可以忽略这种行为?我想在按下Ctrl键时全局更改/移除焦点,但不知道如何实现...

c# wpf
1个回答
0
投票

我还没有尝试过,但是对我来说似乎很合逻辑。

您可以处理按钮的KeyDown和/或PreviewKeyDown事件,并跳过Space的按下。这样的事情可能会起作用:

private void GlobalButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
 if (e.Key == Key.Space)
 e.Handled = true;
}

想知道如何对所有按钮执行此操作?只需在window_load或类似事件上遍历它们即可:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : 
DependencyObject
{
if (depObj != null)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
        if (child != null && child is T)
        {
            yield return (T)child;
        }

        foreach (T childOfChild in FindVisualChildren<T>(child))
        {
            yield return childOfChild;
        }
    }
}
}

/// Looping through the buttons

foreach (Button btn in FindVisualChildren<Button>(this))
{
  btn.KeyDown += GlobalButton_PreviewKeyDown;
  btn.PreviewKeyDown += GlobalButton_PreviewKeyDown;
}

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.