using System.Runtime.InteropServices;[DllImport("User32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("User32.dll")] static extern int GetWindowLong(IntPtr hWnd, int nIndex); public const int GWL_STYLE = -16; public const int ES_NUMBER = 0x2000; private void Form1_Load(object sender, EventArgs e) { SetWindowLong(textBox1.Handle, GWL_STYLE, GetWindowLong(textBox1.Handle, GWL_STYLE) | ES_NUMBER); }// orprivate void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = "0123456789".IndexOf(e.KeyChar) < 0; }
判断是否只含数字 private bool isNum(string keyChar) { int i = 0; char c; for (i = 0; i < keyChar.Length; i++) { c = keyChar[i]; if (!(c >= 48 && c <= 57)) { return false; } } return true; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= (char)48 && e.KeyChar <= (char)57)
{
e.Handled = false;
}
else
{
e.Handled = true;
} }
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("User32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public const int GWL_STYLE = -16;
public const int ES_NUMBER = 0x2000;
private void Form1_Load(object sender, EventArgs e)
{
SetWindowLong(textBox1.Handle, GWL_STYLE,
GetWindowLong(textBox1.Handle, GWL_STYLE) | ES_NUMBER);
}// orprivate void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = "0123456789".IndexOf(e.KeyChar) < 0;
}
private bool isNum(string keyChar)
{
int i = 0;
char c;
for (i = 0; i < keyChar.Length; i++)
{
c = keyChar[i];
if (!(c >= 48 && c <= 57))
{
return false;
}
}
return true;
}
设置maxlenth属性,你的情况是填写10
在KeyDown事件带入方法