KeyUp、keyPress、keyDown的简单理解

对于处理各种普通字符来说,使用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
            {

            }

        }

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值