I'm trying to override the mousewheel control so that when the mouse wheel is moved up or down it only increases the value in the numericupdown field by 1. I believe it is currently using what is stored in the control panel and increasing/decreasing the value by 3 each time.
I'm using the following code. Even when numberOfTextLinesToMove is only 1 and I see that txtPrice.Value is getting populated as expected, something else is overwriting it because the value I set is not what is displayed in the numericupdown box
void txtPrice_MouseWheel(object sender, MouseEventArgs e)
{
int numberOfTextLinesToMove = e.Delta / 120;
if (numberOfTextLinesToMove > 0)
{
txtPrice.Value = txtPrice.Value + (txtPrice.Increment * numberOfTextLinesToMove);
}
else
{
txtPrice.Value = txtPrice.Value - (txtPrice.Increment * numberOfTextLinesToMove);
}
}
The user3610013's answer is working very well. This is a slight modification and may be handy to someone.
private void ScrollHandlerFunction(object sender, MouseEventArgs e)
{
NumericUpDown control = (NumericUpDown)sender;
((HandledMouseEventArgs)e).Handled = true;
decimal value = control.Value + ((e.Delta > 0) ? control.Increment : -control.Increment);
control.Value = Math.Max(control.Minimum, Math.Min(value, control.Maximum));
}
After looking around at similar questions, I discovered that you can also work around this without creating a subclass - for example, this code will give you a numericUpDown that will only scroll by one (and only when the control has focus).
Set up the delegate in the container's constructor:
numericUpDown1.MouseWheel += new MouseEventHandler(this.ScrollHandlerFunction);
... then define the function elsewhere in the class:
private void ScrollHandlerFunction(object sender, MouseEventArgs e)
{
HandledMouseEventArgs handledArgs = e as HandledMouseEventArgs;
handledArgs.Handled = true;
numericUpDown1.Value += (handledArgs.Delta > 0) ? 1 : -1;
}
You should also check to make sure that you're not trying to scroll out of the control's range, because that will crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With