winform input 输入数值(可以小数,负数)
public partial class UCNumberBox : UserControl
{
public UCNumberBox()
{
InitializeComponent();
}
private bool _IsDecimal = true;
/// <summary>
/// 是否为小数,默认为小数
/// </summary>
public bool IsDecimal
{
get { return _IsDecimal; }
set
{
_IsDecimal = value;
if (!value && this.tbValue.Text.IndexOf('.') >= 0)
{
tbValue.Text = tbValue.Text.Substring(0, tbValue.Text.IndexOf('.'));
tbValue.SelectionStart = tbValue.Text.Length;
}
if (value && _Precision == 0)
{
_Precision = 2;
}
}
}
private int _Precision = 2;
public int Precision
{
get { return _Precision; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(Precision), "精度不能小于0");
}
_Precision = value;
if (value == 0)
{
_IsDecimal = false;
}
}
}
private void tbValue_KeyPress(object sender, KeyPressEventArgs e)
{
// 先排除非需要的字符
if (!char.IsDigit(e.KeyChar)
&& e.KeyChar != '.'
&& e.KeyChar != '-'
&& e.KeyChar != '.'
&& e.KeyChar != '\b')
{
e.Handled = true;
}
if (e.Handled || e.KeyChar == '\b')
{
return;
}
// 去掉0开头的证书,类似:0123
if (tbValue.Text == "0" && char.IsDigit(e.KeyChar))
{
if (e.KeyChar != '0')
{
tbValue.Text = e.KeyChar.ToString();
tbValue.SelectionStart = 1;
}
e.Handled = true;
}
// 负号只能出现在第一位
else if (tbValue.Text.Length > 0 && (e.KeyChar == '-'))
{
e.Handled = true;
}
// 排除 -0123这种
else if (tbValue.Text == "-0" && char.IsDigit(e.KeyChar))
{
if (e.KeyChar != '0')
{
tbValue.Text = "-" + e.KeyChar.ToString();
tbValue.SelectionStart = 2;
}
e.Handled = true;
}
//整数,不能出现小数点
if (!IsDecimal && e.KeyChar == '.')
{
e.Handled = true;
}
// 小数
else if (IsDecimal)
{
if (e.KeyChar == '.')
{
// 替换小数点开头的=》0.
if (tbValue.Text.Length == 0)
{
tbValue.Text = "0.";
tbValue.SelectionStart = 2;
e.Handled = true;
}
// 不能重复插入小数点
else if (tbValue.Text.IndexOf('.') >= 0)
{
e.Handled = true;
}
IsInputD = !e.Handled;
}
if (!e.Handled && tbValue.Text.IndexOf('.') >= 0)
{
// 校验小数位数
var ss = tbValue.Text.Split('.');
if (ss[1].Length >= Precision)
{
e.Handled = true;
}
}
}
}
private bool IsInputD = false;
private void tbValue_TextChanged(object sender, EventArgs e)
{
// 在中间插入小数时,需要保证小数位数不超出指定精度
if (IsInputD)
{
IsInputD = false;
var ss = tbValue.Text.Split('.');
if (ss[1].Length > Precision)
{
var format = "".PadLeft(Precision, '0');
tbValue.Text = double.Parse(tbValue.Text).ToString("0." + format);
tbValue.SelectionStart = tbValue.Text.Length;
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器