#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.

Advertisement

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

3 Responses to #685 – Capturing the Mouse

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

  2. Pingback: #687 – What Happens If You Forget to Release The Mouse « 2,000 Things You Should Know About WPF

  3. Pingback: #691 – IsMouseCaptured Indicates Whether Mouse Is Currently Captured « 2,000 Things You Should Know About WPF

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: