在C#中,TextBox控件对输入字符的控制有keypress、keyup、和keydown事件来使用,但大家也看到了,这几个事件对输入字符的控制都有一定的缺陷,如果,你使用中文输入法,那么很多原来你不希望输入的字符也可以输入进去。
private System.Windows.Forms.TextBox textBox1; private string text; public Form1() { text = textBox1.Text; } private void textBox1_TextChanged(object sender, System.EventArgs e) { int len = text.Length; if(len < textBox1.Text.Length) { int index = textBox1.Text.IndexOf(text); char c = (textBox1.Text.Remove(index,text.Length))[0]; if(c.CompareTo(‘0‘) < 0||c.CompareTo(‘9‘) >0) { textBox1.Text = text; textBox1.SelectionStart = text.Length; } } text = textBox1.Text; } |
|