C#按键不捕获“删除”键 [英] C# keypress doesn't capture 'delete' key

查看:121
本文介绍了C#按键不捕获“删除”键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了一个的ListView 按键事件。随着我的事件断点,我可以看到,大部分的按键触发事件。但是,有少数其中,一个我感兴趣的(删除),就不会触发我的事件。



是很奇怪吗?不,还有我的键盘上没有断键:D



 私人无效listView1_KeyPress(对象发件人,KeyPressEventArgs E)
{
如果(e.KeyChar ==(char)的Keys.Delete)
{
ListView的目标=(ListView控件)发送;
如果(target.SelectedIndices = NULL&放大器;!&安培; target.SelectedIndices.Count大于0)
{
串RIC = target.SelectedItems [0] .SubItems [0]。文本;
//target.Items.RemoveAt(target.SelectedIndices[0]);
ListModels.getInstance()getModel(二卷)removeRic(RIC)。
}
}
}


解决方案

这样做的原因是,KeyPress事件发送字符到基于按下字符键的控制。然而,正如你所期望的,删除键不表示一个字符,因此是一个非字符键。



因此​​,使用按键事件会做什么,你已经注意到了。您应该使用在KeyDown或事件的KeyUp,否则将工作精绝。的细微差别是,你是否希望你的事件触发后不放,或按一个键。



希望这有助于! :)



编辑:更新的回答更加清晰。


I have added a keyPress event on a ListView. With a breakpoint on my event, I can see that most of the keys trigger the event. However, a few among which, the one I'm interested in (delete), just won't trigger my event.

Is that weird ? And no, there's no broken keys on my keyboard :D

    private void listView1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Delete)
        {
            ListView target = (ListView)sender;
            if (target.SelectedIndices != null && target.SelectedIndices.Count > 0)
            {
                string ric = target.SelectedItems[0].SubItems[0].Text;
                //target.Items.RemoveAt(target.SelectedIndices[0]);
                ListModels.getInstance().getModel("Vols").removeRic(ric);
            }
        }
    }

解决方案

The reason for this is that the KeyPress event sends a character to the control based upon the character-key you press. However, as you'd expect, the delete key does not represent a character and is thus a non-character key.

Therefore using the Keypress event will do nothing as you have noticed. You should use the KeyDown or KeyUp Events, either of which will work absolutely fine. The nuance being whether you want your event to fire upon letting go, or pressing a key.

Hope this helps! :)

EDIT: Updated answer for more clarity.

这篇关于C#按键不捕获“删除”键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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