I there a way to know which item has the focus in and WPF application? Is there a way to monitor all events and methods calls in wpf?
Asked
Active
Viewed 1,364 times
2
-
Did the solution ever work for you? – Carlo Aug 13 '09 at 19:17
-
Actually I used UISpy which does track the focus of items – Ghassan Karwchan Aug 13 '09 at 22:58
-
I used similar tool - Inspect (C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64\inspect.exe). – Der_Meister Feb 05 '18 at 07:18
2 Answers
5
FocusManager.GetFocusedElement(this); // where this is Window1
Here's a full sample (when the app runs, focus a textbox and hit enter)
xaml:
<Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" KeyDown="window1_KeyDown"
Title="Window1" x:Name="window1" Height="300" Width="300">
<StackPanel>
<TextBox x:Name="textBox1" />
<TextBox x:Name="textBox2" />
<TextBox x:Name="textBox3" />
<TextBox x:Name="textBox4" />
<TextBox x:Name="textBox5" />
</StackPanel>
</Window>
C#
using System.Windows;
using System.Windows.Input;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void window1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if(e.Key == Key.Return)
MessageBox.Show((FocusManager.GetFocusedElement(this) as FrameworkElement).Name);
}
}
}

Carlo
- 25,602
- 32
- 128
- 176
1
ok on this page you'll find a solution but it's a bit nasty if you ask me: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a420dc50-b238-4d2e-9209-dfbd98c7a060
It uses the VisualTreeHelper to create a big list of all the controls out there and then asks them is they have the focus by lookin at the IsFocused property.
I would think that there is a better way to do it. Perhaps do a search for Active control or Focussed control in combination with WPF.
EDIT: This topic might be useful How to programmatically navigate WPF UI element tab stops?