C#中的Keypress事件 [英] Keypress event in C#

查看:285
本文介绍了C#中的Keypress事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本框中输入eky,它会在按键事件的标签上打印出来。

但是当我输入密钥时,它不会在标签上打印那个键那个时间。但是下次当我按下它显示标签中的文字。



例如当我在文本框中按2然后在标签中没有任何东西。

但是当我按23然后在标签2就在那里。



我尝试了什么:



private void txtdisount_KeyPress(object sender,KeyPressEventArgs e)

{

if(char.IsNumber(e.KeyChar)|| e .KeyChar =='。')

{



lblDisVal.Text = txtdisount.Text;

< br $>


}



其他

{

e.Handled = e.KeyChar!=(char)Keys.Back;

}



}

解决方
尝试这种



<预郎= C#> lblDisVal.Text = txtdisount.Text + e.KeyChar.ToString();


那是因为KeyPress事件发生在Text属性更新之前 - 如果没有,你将无法使用它阻止用户输入某些键!

使用TextChanged事件进行更新,使用Keypress进行过滤:

  private   void  txtdisount_KeyPress( object  sender,KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar)&& e.KeyChar!= ' 。'
{
e.Handled = e.KeyChar!=()Keys.Back;
}
}

私有 void txtdisount_TextChanged( object sender,EventArgs e)
{
lblDisVal.Text = txtdisount.Text;
}

但是......你可能会更好地使用NumericUpDown控件!


i want to enter eky in textbox which will print it in label on keypress event.
but when i am entering key it is not printing that key in label that time.but next time when i am pressing it shows that text in label.

for e.g when i press "2" in textbox then in label nothing is there.
but when i press "23" then in label "2" is there.

What I have tried:

private void txtdisount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{

lblDisVal.Text = txtdisount.Text;


}

else
{
e.Handled = e.KeyChar != (char)Keys.Back;
}

}

解决方案

try this

lblDisVal.Text = txtdisount.Text + e.KeyChar.ToString();


That's because the KeyPress event occurs before the Text property is updated - if it didn't you wouldn't be able to use it to prevent some keys being entered by the user!
Use the TextChanged event to update, and Keypress to filter:

private void txtdisount_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (!char.IsNumber(e.KeyChar) && e.KeyChar != '.')
        {
        e.Handled = e.KeyChar != (char)Keys.Back;
        }
    }

private void txtdisount_TextChanged(object sender, EventArgs e)
    {
    lblDisVal.Text = txtdisount.Text;
    }

But...you'd probably be better off using a NumericUpDown control instead!


这篇关于C#中的Keypress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆