Search code examples
c#winformsmousewheelnumericupdown

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

        }

Solution

  • This is a bug reported here: NumericUpDown - use of mouse wheel may result in different increment

    Microsoft's response in Feb 2007 states they cannot address this Visual Studio 2008.

    There are two posted workarounds, both of which subclass NumericUpDown. Check the Workaround tab on the link.

    The one I tried worked for me (posted by 'NanoWizard'):

    using System;
    using System.Windows.Forms;
    
    internal class NumericUpDownControl : NumericUpDown
    {
    #region Constants
    protected const String UpKey = "{UP}";
    protected const String DownKey = "{DOWN}";
    #endregion Constants
    
    #region Base Class Overrides
    protected override void OnMouseWheel(MouseEventArgs e_)
    {
        String key = GetKey(e_.Delta);
        SendKeys.Send(key);
    }
    #endregion Base Class Overrides
    
    #region Protected Methods
    protected static String GetKey(int delta_)
    {
        String key = (delta_ < 0) ? DownKey : UpKey;
        return key;
    }
    #endregion Protected Methods
    }