[英]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.我有一个 C# WinForm 应用程序,我想在其中实现一个 NumericUpDown 组件,该组件根据单击箭头按钮时是否按下控制键来递增/递减其值。 If the control key is pressed, it should increment by 1, by 0.1 otherwise.
如果按下控制键,它应该增加 1,否则增加 0.1。 Using the ValueChanged event does not work, because the value has already changed.
使用 ValueChanged 事件不起作用,因为该值已经更改。 I also tried to use the Click and MouseClick event but they are risen after the ValueChanged Event.
我还尝试使用 Click 和 MouseClick 事件,但它们在 ValueChanged 事件之后出现。
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
}
You can implement it at form level.您可以在表单级别实现它。
https://learn.microsoft.com/en-us/do.net/desktop/winforms/input-keyboard/how-to-handle-forms?view.netdesktop-6.0 https://learn.microsoft.com/en-us/do.net/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.处理启动窗体的KeyPress或KeyDown事件,将窗体的
KeyPreview
属性设置为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;
}
}
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.一种方法是创建一个
CustomNumericUpDown
控件并在您的设计器文件中换出常规NumericUpDown
控件的所有实例。
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.然后,您可以只覆盖在源头上上下实现值的方法,并根据
Control.ModifierKeys
属性的 static 值调用基数 class 或不调用。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.