这个:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx
...表示我应该可以在 KeyPress 事件中访问 e.KeyCode,但我似乎没有。我试图只允许 1、2、3 和退格键:
private void textBoxQH1_KeyPress(object sender, KeyPressEventArgs e) {
if ((e.KeyChar != '1') &&
(e.KeyChar != '2') &&
(e.KeyChar != '3') &&
(e.KeyChar != (Keys.Back))) {
e.Handled = true;
}
}
...但是“e”。不显示像示例所示的“KeyCode”值,并且尝试使用 KeyChar 和 Keys.Back 责骂我,“运算符 '!=' 不能应用于类型 'char' 和 'System.Windows.Forms.Keys' 的操作数”
那么我怎样才能做到这一点呢?
我很确定我只是通过使用
KeyDown
事件来解决这个问题;它有不同的事件参数。
尝试设置这样的条件:
代码:
if (e.KeyCode == (Keys.Back))
{
if(textBox1.Text.Length >=3)
{
if (textBox1.Text.Contains("-"))
{
textBox1.Text.Replace("-", "");
}
}
}
我需要在用退格键删除所有文本框内容后添加0(如果最后一次击键满足退格条件), 同时仍然清除按键时的文本框和文本框 仅包含零(当第一次将输入放入文本框中时,Form1.cs [Desigh] Properties Text 设置为 0):
private void textBox14_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox14.Text == "0")
textBox14.Clear();
if (e.KeyChar == ((char)Keys.Back))
{
if (textBox14.Text.Length <= 1)
{
textBox14.Text = "0";
}
}
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-' || e.KeyChar == '.') return;
if (!Char.IsControl(e.KeyChar))
e.Handled = true;
}