前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何追踪 WPF 程序中当前获得键盘焦点的元素并显示出来

如何追踪 WPF 程序中当前获得键盘焦点的元素并显示出来

作者头像
walterlv
发布2023-10-22 10:20:41
3800
发布2023-10-22 10:20:41
举报

我们有很多的调试工具可以帮助我们查看 WPF 窗口中当前获得键盘焦点的元素。本文介绍监控当前键盘焦点元素的方法,并且提供一个不需要任何调试工具的自己绘制键盘焦点元素的方法。


使用调试工具查看当前获得键盘焦点的元素

Visual Studio 带有实时可视化树的功能,使用此功能调试 WPF 程序的 UI 非常方便。

在打开实时可视化树后,我们可以略微认识一下这里的几个常用按钮:

这里,我们需要打开两个按钮:

  • 为当前选中的元素显示外框
  • 追踪具有焦点的元素

这样,只要你的应用程序当前获得焦点的元素发生了变化,就会有一个表示这个元素所在位置和边距的叠加层显示在窗口之上。

你可能已经注意到了,Visual Studio 附带的这一叠加层会导致鼠标无法穿透操作真正具有焦点的元素。这显然不能让这一功能一直打开使用,这是非常不方便的。

使用代码查看当前获得键盘焦点的元素

我们打算在代码中编写追踪焦点的逻辑。这可以规避 Visual Studio 中叠加层中的一些问题,同时还可以在任何环境下使用,而不用担心有没有装 Visual Studio。

获取当前获得键盘焦点的元素:

1

var focusedElement = Keyboard.FocusedElement;

不过只是拿到这个值并没有多少意义,我们需要:

  1. 能够实时刷新这个值;
  2. 能够将这个控件在界面上显示出来。

实时刷新

Keyboard 有路由事件可以监听,得知元素已获得键盘焦点。

1

Keyboard.AddGotKeyboardFocusHandler(xxx, OnGotFocus);

这里的 xxx 需要替换成监听键盘焦点的根元素。实际上,对于窗口来说,这个根元素可以唯一确定,就是窗口的根元素。于是我可以写一个辅助方法,用于找到这个窗口的根元素:

1 2 3 4 5 6 7 8 9

// 用于存储当前已经获取过的窗口根元素。 private FrameworkElement _root; // 获取当前窗口的根元素。 private FrameworkElement Root => _root ?? (_root = FindRootVisual(this)); // 一个辅助方法,用于根据某个元素为起点查找当前窗口的根元素。 private static FrameworkElement FindRootVisual(FrameworkElement source) => (FrameworkElement)((HwndSource)PresentationSource.FromVisual(source)).RootVisual;

于是,监听键盘焦点的代码就可以变成:

1 2 3 4 5 6 7 8 9

Keyboard.AddGotKeyboardFocusHandler(Root, OnGotFocus); void OnGotFocus(object sender, KeyboardFocusChangedEventArgs e) { if (e.NewFocus is FrameworkElement fe) { // 在这里可以输出或者显示这个获得了键盘焦点的元素。 } }

显示

为了显示一个跟踪焦点的控件,我写了一个 UserControl,里面的主要代码是:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

<Canvas IsHitTestVisible="False"> <Border x:Name="FocusBorder" BorderBrush="#80159f5c" BorderThickness="4" HorizontalAlignment="Left" VerticalAlignment="Top" IsHitTestVisible="False" SnapsToDevicePixels="True"> <Border x:Name="OffsetBorder" Background="#80159f5c" Margin="-200 -4 -200 -4" Padding="12 0" HorizontalAlignment="Center" VerticalAlignment="Bottom" SnapsToDevicePixels="True"> <Border.RenderTransform> <TranslateTransform x:Name="OffsetTransform" Y="16" /> </Border.RenderTransform> <TextBlock x:Name="FocusDescriptionTextBlock" Foreground="White" HorizontalAlignment="Center" /> </Border> </Border> </Canvas>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

using System; using System.Runtime.InteropServices; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Threading; namespace Walterlv.Windows { public partial class KeyboardFocusView : UserControl { public KeyboardFocusView() { InitializeComponent(); Loaded += OnLoaded; Unloaded += OnUnloaded; } private void OnLoaded(object sender, RoutedEventArgs e) { if (Keyboard.FocusedElement is FrameworkElement fe) { SetFocusVisual(fe); } Keyboard.AddGotKeyboardFocusHandler(Root, OnGotFocus); } private void OnUnloaded(object sender, RoutedEventArgs e) { Keyboard.RemoveGotKeyboardFocusHandler(Root, OnGotFocus); _root = null; } private void OnGotFocus(object sender, KeyboardFocusChangedEventArgs e) { if (e.NewFocus is FrameworkElement fe) { SetFocusVisual(fe); } } private void SetFocusVisual(FrameworkElement fe) { var topLeft = fe.TranslatePoint(new Point(), Root); var bottomRight = fe.TranslatePoint(new Point(fe.ActualWidth, fe.ActualHeight), Root); var isOnTop = topLeft.Y < 16; var isOnBottom = bottomRight.Y > Root.ActualHeight - 16; var bounds = new Rect(topLeft, bottomRight); Canvas.SetLeft(FocusBorder, bounds.X); Canvas.SetTop(FocusBorder, bounds.Y); FocusBorder.Width = bounds.Width; FocusBorder.Height = bounds.Height; FocusDescriptionTextBlock.Text = string.IsNullOrWhiteSpace(fe.Name) ? $"{fe.GetType().Name}" : $"{fe.Name}({fe.GetType().Name})"; } private FrameworkElement _root; private FrameworkElement Root => _root ?? (_root = FindRootVisual(this)); private static FrameworkElement FindRootVisual(FrameworkElement source) => (FrameworkElement)((HwndSource)PresentationSource.FromVisual(source)).RootVisual; } }

这样,只要将这个控件放到窗口中,这个控件就会一直跟踪窗口中的当前获得了键盘焦点的元素。当然,为了最好的显示效果,你需要将这个控件放到最顶层。

绘制并实时显示 WPF 程序中当前键盘焦点的元素

如果我们需要监听应用程序中所有窗口中的当前获得键盘焦点的元素怎么办呢?我们需要给所有当前激活的窗口监听 GotKeyboardFocus 事件。

于是,你需要我在另一篇博客中写的方法来监视整个 WPF 应用程序中的所有窗口:

里面有一段对 ApplicationWindowMonitor 类的使用:

1 2 3 4 5 6 7 8 9

var app = Application.Current; var monitor = new ApplicationWindowMonitor(app); monitor.ActiveWindowChanged += OnActiveWindowChanged; void OnActiveWindowChanged(object sender, ActiveWindowEventArgs e) { var newWindow = e.NewWindow; // 一旦有一个新的获得焦点的窗口出现,就可以在这里执行一些代码。 }

于是,我们只需要在 OnActiveWindowChanged 事件中,将我面前面写的控件 KeyboardFocusView 从原来的窗口中移除,然后放到新的窗口中即可监视新的窗口中的键盘焦点。

由于每一次的窗口激活状态的切换都会更新当前激活的窗口,所以,我们可以监听整个 WPF 应用程序中所有窗口中的键盘焦点。

本文会经常更新,请阅读原文: https://blog.walterlv.com/post/how-to-track-wpf-focused-element.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 吕毅 (包含链接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 ([email protected])

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用调试工具查看当前获得键盘焦点的元素
  • 使用代码查看当前获得键盘焦点的元素
    • 实时刷新
      • 显示
      • 绘制并实时显示 WPF 程序中当前键盘焦点的元素
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档