Ghassan Karwchan
Ghassan Karwchan

Reputation: 3530

Is there a way to know which item has the focus in a WPF application?

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?

Upvotes: 2

Views: 1760

Answers (2)

Carlo
Carlo

Reputation: 25959

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

Upvotes: 5

Yvo
Yvo

Reputation: 19263

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?

Upvotes: 1

Related Questions