There are two functions which helps in capturing mouse input, it’s called SetCapture and ReleaseCapture and a helper function called GetCapture which returns a handle to the capture window associated with the current thread. If no window in the thread has captured the mouse, the return value is NULL.
Why do we need to capture mouse?
An example is when doing rubber band drawing. If mouse goes out of our window we won’t be able to get mouse movement events, but with a call to SetCapture this will be possible as a result our line keeps moving vertically and horizontally according to mouse movement. Ideal flow for drawing rubber band lines should be…
- OnLButtonDown – Capture mouse using SetCapture
- OnMouseMove – We’ll continue drawing rubber band lines, also clear previous line.
- OnLButtonUp – Release mouse using ReleaseCapture
- Neatly handle WM_CAPTURECHANGED just in case in someone captures mouse in between the drawing process.
Some points to note…
- Only one window at a time can capture mouse input.
- Only the foreground window can capture mouse input.
- Background windows can capture mouse input but they’ll receive mouse notifications only when mouse moves over their visible region.
- Menu hotkeys and accelerators don’t work when mouse is captured.
Don’t forget to handle WM_CAPTURECHANGED message, because if another window calls SetCapture then this message is fired to the window that is losing mouse capture. To release captured mouse call ReleaseCapture.