- 打卡等级:常驻代表
- 打卡总天数:34
- 打卡月天数:6
- 打卡总奖励:9027
- 最近打卡:2025-12-17 23:15:51
管理员
- 积分
- 22569
|
Winform TextBox (文本框) 控件只能输入数值, 限制输入两位小数- using System;
- using System.Windows.Forms;
-
- namespace DemoWinForm
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- }
-
- /// <summary>
- /// 文本框 - 只能输入数值, 限制输入两位小数
- /// 禁止粘贴
- /// </summary>
- public class TextBoxExFloat : TextBox
- {
- /// <summary>
- /// 构造函数
- /// </summary>
- public TextBoxExFloat()
- {
- }
-
- #region 禁止粘贴
- /// <summary>
- /// 重写基类的WndProc方法
- /// </summary>
- /// <param name="m"></param>
- protected override void WndProc(ref Message m)
- {
- if (m.Msg == 0x0302) // 0x0302是粘贴消息
- {
- m.Result = IntPtr.Zero; // 拦截此消息
- return;
- }
- base.WndProc(ref m); // 若此消息不是粘贴消息,则交给其基类去处理
- }
- #endregion
-
- #region 重写方法
- /// <summary>
- /// 重写方法
- /// 可以输入小数
- /// </summary>
- /// <param name="e"></param>
- protected override void OnKeyPress(KeyPressEventArgs e)
- {
- base.OnKeyPress(e);
- if (e.KeyChar != 8)// 允许输入退格键
- {
- // 最多8位数金额
- if (this.Text.Length == 8) { e.Handled = true; }
-
- // 允许输入数字、小数点
- if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != (char)('.'))
- {
- e.Handled = true;
- }
-
- // 小数点只能输入一次
- if (e.KeyChar == (char)('.') && this.Text.IndexOf('.') != -1)
- {
- e.Handled = true;
- }
-
- // 第一位不能为小数点
- if (e.KeyChar == (char)('.') && this.Text == "")
- {
- e.Handled = true;
- }
-
- // 第一位是0,第二位必须为小数点
- if (e.KeyChar != (char)('.') && this.Text == "0")
- {
- e.Handled = true;
- }
-
- // 有小数只保留2位
- if (this.Text.IndexOf('.') != -1)
- {
- if (this.Text.Length - this.Text.IndexOf('.') - 1 == 2)
- {
- e.Handled = true;
- }
- }
- }
- }
- #endregion
-
- }
- }
复制代码
拖拽“TextBoxExFloat”的自定义控件到窗体
|
|