尝试在C#中执行按键事件时出错

时间:2014-01-16 08:39:50

标签: c# events keypress

我添加了按键事件

private void listView_KeyPress(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        DeleteContact();
    }
}

框架自动为它创建类:

this.listView.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress);

编译时我在System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress)

上收到错误
No overload for 'listView_KeyPress' matches delegate 'System.Windows.Forms.KeyPressEventHandler'    D:\...\MainForm.Designer.cs

感谢任何有用的答案,谢谢。

4 个答案:

答案 0 :(得分:2)

KeyPress事件需要参数KeyPressEventArgs而不是KeyEventArgs

但是KeyPress事件只会为您提供所按键的字符。并且DELETE键没有字符。因此,您应该使用事件KeyDown,因为这个事件会为您提供KeyCode:

this.listView.KeyDown+= new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyDown);

private void listView_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        DeleteContact();
    }
}

答案 1 :(得分:0)

KeyPressEventHandler委托要求第二个参数为KeyPressEventArgs个对象,而不是KeyEventArgs

private void listView_KeyPress(object sender, KeyPressEventArgs e)

如果您需要使用KeyEventArgs中的信息,则应使用KeyDown事件。如果是这样,请注意,如果用户按下该键,则可以多次引发KeyDown事件。

答案 2 :(得分:0)

请参阅 KeyPressEventHandler

private void listView_KeyPress(object sender, KeyEventArgs e)

必须更改为

private void listView_KeyPress(object sender, KeyPressEventArgs e)

答案 3 :(得分:0)

你的签名错了。处理程序中的e参数应为KeyPressEventArgs而不是KeyEventArgs