问题
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.
回答1:
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.
回答2:
This is a bit crude but it's a little simpler than the other answer (not better though) and for the 2nd part of the question you just need to replace the 100/10/1 with a calculation based on the current value.
Set the default incrememnt to 100 (or whatever) and in the keydown event of the NumericUpDown
(nUpDown)
private void nUpDown_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Up)
nUpDown.Value += 10;
else if (e.Control && e.KeyCode == Keys.Down)
nUpDown.Value -= 10;
else if (e.Shift && e.KeyCode == Keys.Up)
nUpDown.Value += 1;
else if (e.Shift && e.KeyCode == Keys.Down)
nUpDown.Value -= 1;
}
来源:https://stackoverflow.com/questions/6961226/variable-increment-step-in-winform-numericupdown-control-depending-on-whether-sh