Home > database >  NumericUpDown with different increment values
NumericUpDown with different increment values

Time:01-31

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

}

CodePudding user response:

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

CodePudding user response:

You can implement it at form level.
https://learn.microsoft.com/en-us/dotnet/desktop/winforms/input-keyboard/how-to-handle-forms?view=netdesktop-6.0

Handle the KeyPress or KeyDown event of the startup form, and set the KeyPreview property of the form to true.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.ControlKey)
    {
        numSetPoint1.Increment = 1;
    }
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.ControlKey)
    {
        numSetPoint1.Increment = 0.1m;
    }
}
  • Related