2

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?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Ghassan Karwchan
  • 3,355
  • 7
  • 37
  • 65

2 Answers2

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?

Community
  • 1
  • 1
Yvo
  • 18,681
  • 11
  • 71
  • 90