Tuesday, 3 November 2009

Mouse Wheel Events in Windows WPF

Handling mouse wheel events is not straightforward like mouse clicks and needs a fuller explanation.

A mouse wheel can be rotated in either direction and contain notches restricting small changes in rotation, to about 15 degrees per notch. The problem is that there is no standard to the values produced by a mouse wheel, it is all hardware specific. Different mice will return provide different delta values for the same physical movement by the same user.

So the most accurate way to handle a mouse wheel event is to write a hardware specific code, which is clearly not a viable option.

An alternative is to treat all mouse wheel events as the same, all equaling one notch. This is not too bad as Windows fires mouse wheel events very quickly. However if the user moves the wheel quickly then only one event will be generated for multiple notches.

The solution I came up with calibrates the value of a notch as it receives mouse wheel events and is therefore not dependent on specific values. It has proved to reliable in practice.

private int minMouseDelta = 1000000;
A instance variable stores the lowest delta of the mouse, this is initially set extremely high.
void process_MouseWheel(object sender, MouseWheelEventArgs e)
int absDelta = Math.Abs(e.Delta);

The mouse wheel event contains a int delta value that indicates how much the wheel has been rotated. The sign of the value indicates the direction of the rotation but the value is hardware specific.

The first thing we do is to discard the sign so we only need to work with possitive values.

if ((minMouseDelta > absDelta) && (absDelta > 0))
minMouseDelta = absDelta;

The delta is compared with the minimum delta so far observed and if it is smaller then the minimum value is updated. After several events, usually just one, we can then be certain of the smallest delta change made by the wheel. This is treated as one notch.

int factor = absDelta / minMouseDelta;
if (factor < 1)
    factor = 1;

We can then calculate how many notches the current events delta contains. This is stored in the variable factor.

No comments:

Post a Comment