views:

298

answers:

1

I have a Silverlight game controlled by the keyboard, and I want it to go into pause when it loses the keyboard focus (e.g. the user clicks on another part of the hosting webpage, or moves to another browser tab).

I used to do this in Silverlight 1.1 by subscribing to the LostFocus event on my RootVisual UserControl, but in the last two versions of Silverlight, I have found this event seems to fire unexpectedly shortly after clicking a button in my application (in Silverlight 2 it fired once, in Silverlight 3 twice!).

Is there a way in javascript on the hosting page, or within Silverlight to detect loss of focus more reliably?

+2  A: 

I finally found a solution to this problem. The RoutedEventArgs property on the LostFocus event has an OriginalSource property which allows me to ignore any LostFocus events that come from children of the RootVisual.

    void Page_LostFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource == this)
        {
            Pause();
        }
    }
Mark Heath
Are you sure this works? In my experience, when a child has focus and the focus is transfered outside of both the parent and the child, you never get a LostFocus with OriginalSource == parent.I don't bother listening for LostFocus. I do everything in GotFocus.
Bruno Martinez
I guess its possible that there are some scenarios in which this isn't reliable, but for my game it works fine. Would be a nice update to Silverlight to have a global event you can subscribe to at the application level.
Mark Heath