#685 – Capturing the Mouse

When you are handling mouse events, the event is generally fired by the control that the mouse is over.  For example, if you hold down the mouse button over one control, move the mouse, and release over another control, the first control will see the MouseDown event and the second will see the MouseUp event.

A control can request that it receive all future mouse events by executing the CaptureMouse event.  When it sees the event it was waiting for, it can then call the ReleaseMouseCapture event to go back to normal behavior.

        private void MouseDown_Raph(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Raphael sees MouseDown");
            ((UIElement)e.Source).CaptureMouse();
        }

        private void MouseUp_Raph(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Raphael sees MouseUp");
            ((UIElement)e.Source).ReleaseMouseCapture();
        }

With the code above, the “Raphael” label captures the mouse on a MouseDown, allowing it to see the corresponding MouseUp event, no matter where the mouse pointer is moved.

Advertisements