Mark Heath
Mark Heath

Reputation: 49522

Detecting loss of keyboard focus in a Silverlight application

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?

Upvotes: 2

Views: 1032

Answers (1)

Mark Heath
Mark Heath

Reputation: 49522

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

Upvotes: 2

Related Questions