我为了让textbox只能输入数字,我用了一个正则表达式代码如下:
if(Regex.IsMatch(e.KeyChar.ToString(),"[^0-9]")&&e.KeyChar!=8)
{
e.Handled=true;
}
可是当我改变输入法时,比如改变在中文输入法下,又可以输入字符了,为什么呢?
if(Regex.IsMatch(e.KeyChar.ToString(),"[^0-9]")&&e.KeyChar!=8)
{
e.Handled=true;
}
可是当我改变输入法时,比如改变在中文输入法下,又可以输入字符了,为什么呢?
你在TextChanged事件里再加个判断
using System.Runtime.InteropServices;[DllImport("User32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("User32.dll")]
private 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);
}