Search code examples
c#winformsvisual-studio-2010.net-4.0numericupdown

Variable increment step in WinForm NumericUpDown control depending on whether Shift/Ctrl/etc. are pressed


What I want is somewhat similar to what happens in a WinForm designer in Visual Studio, say VS2010. If I place a button and select it and use arrow keys, it will move around by 5 pixels in whatever direction I chose by pressing the right key. Now, if I hold either a Shift or a Ctrl modifier as I do that (forgot which one, sorry), then the button will move only by 1 pixel at a time.

I want this to happen with my NumericUpDown control in a C# WinForm app. Let's say a default increment is 100.0, and a smaller increment is 10.0. An even smaller increment (if possible) can be 1.0. Any hints on how can I do that?

Hopefully I do not need to ask this as a separate question: I am also toying with the idea of having the increment be dependent on the current value entered. Say, I can enter a dollar amount anywhere between 1 and 100 billion. I then want the default, small, and smaller increment values be dependent on the value entered. I can figure out the exact formula myself.


Solution

  • Derive your own class from NumericUpDown and override the UpButton() and DownButton() methods:

    using System;
    using System.Windows.Forms;
    
    public class MyUpDown : NumericUpDown {
        public override void UpButton() {
            decimal inc = this.Increment;
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control) this.Increment *= 10;
            base.UpButton();
            this.Increment = inc;
        }
        // TODO: DownButton
    }
    

    Tweak as necessary to give other keys different effects.