2

I'm trying to debug some issues with missing/extra tab stops. Is there some kind of global event that I can attach to so that I can log which element got focus whenever focus changes? Thanks! Here's what I'm doing right now, which works well enough, but I'm still curious as to whether there's another way:

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.2);
timer.Tick += onTick;
timer.Start();

// ...

private object LastFocusedElement;
private void onTick(object sender, EventArgs e)
{
    object elem = FocusManager.GetFocusedElement();
    if(LastFocusedElement != elem)
    {
        LastFocusedElement = elem;
        System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
    }
}
Robert Fraser
  • 10,649
  • 8
  • 69
  • 93

2 Answers2

2

You should be able to subscribe to the GotFocus event for the "top-most" container. I don't see any Handled flag for RoutedEventArgs so as far as I can tell, it should always reach it

<UserControl ...
             GotFocus="UserControl_GotFocus">
    <!-- Lots of Nested Controls -->
</UserControl>

private void UserControl_GotFocus(object sender, RoutedEventArgs e)
{
    object elem = e.OriginalSource;
    System.Diagnostics.Debug.WriteLine("+++FOCUS+++ Focus changed to: " + elem + (elem == null ? "" : " (" + elem.GetType().Name + ")"));
}
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
-1

You should be able to use AddHandler function to hook up an on focus event with your control.

And look at the AddHandler signature, even an event had been handled you should be able to get a notification as well.

Johnny
  • 363
  • 1
  • 8
  • There is no way to use AddHandler function. You can this.GotFocus += .... but it didn't seem to work for me unless I added the handler in the xaml. AddHander is really useful for mouse events as you can catch already handled events! – Nigel Thorne Feb 13 '13 at 03:45