using System;
using System.Windows.Forms;
namespace DemoWinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
/// <summary>
/// 文本框 - 只能输入整型且第一位不能是0
/// 禁止粘贴
/// </summary>
public class TextBoxExInt : TextBox
{
/// <summary>
/// 构造函数
/// </summary>
public TextBoxExInt()
{
}
#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 != '\b')// 允许输入退格键
{
// 最多8位数金额
if (this.Text.Length == 8) { e.Handled = true; }
// 整型第一个不能输入0
if (this.TextLength == 0)
{
if (e.KeyChar == '0') { e.Handled = true; ; }
}
// 只允许输入0-9数字
if ((e.KeyChar < '0') || (e.KeyChar > '9'))
{
e.Handled = true;
}
}
}
#endregion
}
}
拖拽“TextBoxExInt”的自定义控件到窗体
