#689 – An Application Can Lose Its Mouse Capture

You can capture the mouse on one mouse button event and then release it on another, with your application in some state while the mouse is captured.

For example, changing the background color of a label while the left mouse button is down.

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

Although your code normally releases the mouse capture, it’s also possible that some system event causes the mouse capture to be lost.  (E.g. A system dialog pops up).  In this case, you won’t get the expected event, so your event handler never gets a chance to release the mouse capture.  Your application then ends up in an unacceptable state.  (E.g. Label’s background color wrong).

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #689 – An Application Can Lose Its Mouse Capture

  1. Pingback: Dew Drop – November 14, 2012 (#1,442) | Alvin Ashcraft's Morning Dew

Leave a comment