【问题标题】:Variable increment step in WinForm NumericUpDown control depending on whether Shift/Ctrl/etc. are pressedWinForm NumericUpDown 控件中的可变增量步长取决于是否 Shift/Ctrl/等。被按下
【发布时间】:2011-08-05 18:51:01
【问题描述】:

我想要的有点类似于 Visual Studio 中的 WinForm 设计器中发生的事情,比如 VS2010。如果我放置一个按钮并选择它并使用箭头键,它将在我通过按右键选择的任何方向上移动 5 个像素。现在,如果我同时按住 Shift 或 Ctrl 修饰符(忘记是哪个,抱歉),那么按钮一次只会移动 1 个像素。

我希望在 C# WinForm 应用程序中使用我的 NumericUpDown 控件来实现这一点。假设默认增量为 100.0,较小的增量为 10.0。更小的增量(如果可能)可以是 1.0。关于我该怎么做的任何提示?

希望我不需要将此作为一个单独的问题提出:我也在玩弄让增量取决于输入的当前值的想法。比如说,我可以输入 1 到 1000 亿之间的任何金额。然后,我希望默认的、小的和更小的增量值取决于输入的值。我可以自己弄清楚确切的公式。

【问题讨论】:

    标签: c# winforms visual-studio-2010 .net-4.0 numericupdown


    【解决方案1】:

    从 NumericUpDown 派生您自己的类并覆盖 UpButton() 和 DownButton() 方法:

    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
    }
    

    根据需要进行调整以赋予其他键不同的效果。

    【讨论】:

      【解决方案2】:

      这有点粗略,但比其他答案简单一点(虽然不是更好),对于问题的第二部分,您只需将 100/10/1 替换为基于当前值的计算。

      NumericUpDown (nUpDown) 的 keydown 事件中将默认增量设置为 100(或其他)

      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;
      }
      

      【讨论】:

      • 谢谢,_KeyDown_KeyUp 更可取吗?
      • keydown 会在按键被按住时重复,而 keyup 只会在松开时触发
      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多