Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numericupdown mousewheel event increases decimal more than one increment

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);
            }

        }
like image 944
JonF Avatar asked Mar 07 '11 23:03

JonF


2 Answers

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));
}
like image 138
vjou Avatar answered Sep 18 '22 10:09

vjou


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.

like image 44
user3610013 Avatar answered Sep 21 '22 10:09

user3610013