0

我需要让TextBox控件一次只接受一个字符。例如,如果我输入"aaa",那么它只会接受"a"

我怎样才能做到这一点?

4

2 回答 2

2

TextBox 有一个MaxLength属性。MaxLength获取或设置可以手动输入到文本框中的最大字符数。

 <TextBox MaxLength="1" Width="120" Height="23" />

所以在这里,您只能手动输入一个字符。

于 2013-04-21T18:42:22.287 回答
1

如果我理解正确,您不希望用户能够连续多次输入相同的密钥。这应该防止:

 private void textBox_KeyDown(object sender, KeyEventArgs e)
 {
     TextBox textBox = sender as TextBox;
     if(textBox != null)
     {
         if (!String.IsNullOrEmpty(textBox.Text))
         {
             //get the last character and convert it to a key
             char prevChar = textBox.Text[textBox.Text.Length - 1];
             Keys k = (Keys)char.ToUpper(prevChar);

             //compare the Key pressed to the previous Key
             if (e.KeyData == k)
             {
                 //suppress the keypress if the key is the same as the previous one
                 e.SuppressKeyPress = true;              
             }
         }
     }
 }
于 2013-04-21T18:49:57.160 回答