I noticed that my MouseWheel
event handler is only executed when the mouse pointer is in the window. I want it to run the handler even when the pointer is outside the window.
I only have one window in my program and its XAML is structured as below:
<Window ...
MouseWheel = "Window_MouseWheel">
....
</Window>
In order to receive mouse events when the cursor leaves the window, the window needs to "capture" the mouse. It does this by passing itself to the
Mouse.Capture()
method.Note that if your program window loses activation (i.e. the user task-switches to some other program), it will lose the mouse capture. If you want to automatically track the mouse wheel again when the window is later reactivated by the user, you'll need to handle that specifically (i.e. handle the
Activated
event).Finally note that with mouse capture enabled, the normal interaction with the window via the mouse doesn't work, nor will Alt-F4. You will need to provide the user with some mechanism for additionally interacting with the program (e.g. handle key events).
Below is a simple example program that shows the basic idea:
XAML:
C#:
When the mouse is captured, the window will respond to mouse wheel events regardless of where the cursor is placed. When the mouse is not captured, it responds to the mouse wheel events only when the cursor is over the window.