对于处理各种普通字符来说,使用KeyPress事件进行判断再好不过了。
但KeyPress有其自身的局限性。它不能捕捉功能键的按键事件,如:F1——F12,shift,Ctrl,Alt,Tab,方向键,以及Insert,Home ,print等。
需要对这些按键事件进行处理的时候,请使用KeyDown或KeyUP事件。
当然,KeyDown或KeyUP事件 也可以对各种字符进行处理
首先将KeyPreview属性设置为True;
简单使用举例:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//KeyPress:当在Form1中任意一处输入字符f时(光标在form中),执行下面的事件
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar=='f')
{
MessageBox.Show("form1");
e.Handled = true;
}
}
//当在button1上输入b时,弹出事件框
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'b')
{
MessageBox.Show("button");
e.Handled = true;
}
}
//当在textBox1中输入字符t时,执行事件
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 't')//当我输入1时,发生下面的事件
{
MessageBox.Show(e.KeyChar.ToString ());
e.Handled = true;
}
}
//当我在textBox1中按下Backspace键
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)//当我输入1时,发生下面的事件
{
MessageBox.Show("刚才我按了back键");
e.Handled = true;
}
}
//当我在textBox1中输入A
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.A)
{
textBox1.Text = "刚才我按了A键";
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
int kc = (int)e.KeyChar;
if ((kc < 48 || kc > 57) && kc != 8)
{
MessageBox.Show("不等于8");
e.Handled = true;
}
}
catch
{
}
}
}