You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NumericUpDown的ValueChanged事件前获取文本实现数值快捷换算宏

实现方案

问题根源

你之前的代码使用了Value属性,该属性仅在输入完成(控件失焦、按下回车等操作触发提交)后才会更新,输入过程中的临时编辑内容不会同步到Value中,因此无法拿到你刚输入的数字。

修复后代码

private void NumericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    // 仅处理K/k和M/m按键
    if (e.KeyCode != Keys.K && e.KeyCode != Keys.M) 
        return;

    // 获取当前输入框内的临时文本
    string inputRaw = NumericUpDown1.Text.Trim();
    if (string.IsNullOrEmpty(inputRaw)) 
        return;

    // 校验输入文本是否为合法数值
    if (decimal.TryParse(inputRaw, out decimal inputNum))
    {
        decimal multiple = e.KeyCode == Keys.K ? 1000 : 1000000;
        // 计算后赋值,同时避免超过控件的Maximum限制
        NumericUpDown1.Value = Math.Min(inputNum * multiple, NumericUpDown1.Maximum);
        // 阻止K/M字符输入到文本框
        e.SuppressKeyPress = true;
        e.Handled = true;
    }
}

补充说明

  • 同时支持大小写按键触发,不需要额外判断Shift状态
  • 自动适配NumericUpDown设置的最大值,不会出现赋值越界报错
  • 如果需要支持更大的单位(如G/吉),只需新增对应KeyCode判断,倍率设置为1000000000即可

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:15:04