#690 – Being Notified When Mouse Capture Is Lost

Your application can lose its mouse capture due to some system event.  When this happens, you might want to know that the capture was lost so that you can restore some application state.

You can discover when you’ve lost the mouse capture due to some external event by handling the LostMouseCapture event.

In the example below, the code normally releases the mouse capture and reverts the label’s color on a MouseUp event.  It also reverts the label’s color when it discovers that it has lost the mouse capture.

        private Brush savedBrush;

        private void Feast_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Feast_MouseDown");
            Label l = e.Source as Label;
            l.CaptureMouse();
            savedBrush = l.Background;
            l.Background = Brushes.Cyan;
        }

        private void Feast_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Feast_MouseUp");
            Label l = e.Source as Label;
            l.ReleaseMouseCapture();
            l.Background = savedBrush;
        }

        private void Feast_LostMouseCapture(object sender, MouseEventArgs e)
        {
            Label l = e.Source as Label;
            l.Background = savedBrush;
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: