Search code examples
c#.netwinformsnumericupdown

NumericUpDown with different increment values


I have a C# WinForm application where I want to implement a NumericUpDown component that increments / decrements its value depending whether or not the control key is pressed on clicking to the arrow button. If the control key is pressed, it should increment by 1, by 0.1 otherwise. Using the ValueChanged event does not work, because the value has already changed. I also tried to use the Click and MouseClick event but they are risen after the ValueChanged Event.

Has anyone an Idea how I can achieve this?

// This method added to either Click or MouseClick event
private void Click_Event(object sender, EventArgs e)
{
    if (Control.ModifierKeys == Keys.Control)
    {
        numSetPoint1.Increment = 1; // Setting the Increment value takes effect on the next click
    }
    else
    {
        numSetPoint1.Increment = 0.1m;
    }
}
// Event added to ValueChanged
private void ValueChanged_Event(object sender, EventArgs e)
{
    // the same here

}

Solution

  • One way to do this is by making a CustomNumericUpDown control and swapping out all instances of the regular NumericUpDown control in your designer file.

    Then you can just override the methods that implement the value up-down at the source and call the base class or not depending on the static value of Control.ModifierKeys property.

    class CustomNumericUpDown : NumericUpDown
    {
        public CustomNumericUpDown() => DecimalPlaces = 1;
        public override void UpButton()
        {
            if(ModifierKeys.Equals(Keys.Control))
            {
                Value += 0.1m;
            }
            else
            {
                // Call Default
                base.UpButton();
            }
        }
        public override void DownButton()
        {
            if (ModifierKeys.Equals(Keys.Control))
            {
                Value -= 0.1m;
            }
            else
            {
                base.DownButton();
            }
        }
    }
    

    screenshot