【问题标题】:An error when trying to do key press event in C#尝试在 C# 中执行按键事件时出错
【发布时间】:2014-01-16 08:39:49
【问题描述】:

我添加了一个按键事件

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

如果有任何有用的答案,我将不胜感激,谢谢。

【问题讨论】:

  • 您是否在您拥有的类中定义了方法 listView_KeyPress:this.listView.KeyPress += .... ???
  • 再次删除。您需要 KeyDown 事件来识别 Delete 键。

标签: c# events keypress


【解决方案1】:

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();
    }
}

【讨论】:

  • KeyPressEventArgs 不包含 KeyCode
  • @Mike,不,但它包含 KeyChar
  • 您能否提供一个简单的示例如何使用 KeyChar 处理删除?
  • @Mike 在这种情况下,您需要 keydown 事件。我正在更新我的答案,请稍等
  • 谢谢,每个可能的按钮都一样吗?
【解决方案2】:

您的签名错误。处理程序中的 e 参数应该是 KeyPressEventArgs 而不是 KeyEventArgs

【讨论】:

    【解决方案3】:

    KeyPressEventHandler 委托期望第二个参数是 KeyPressEventArgs 对象,而不是 KeyEventArgs

    private void listView_KeyPress(object sender, KeyPressEventArgs e)
    

    如果您需要使用在KeyEventArgs 中找到的信息,您应该使用KeyDown 事件。如果是这样,请注意KeyDown 事件可能会引发多次,如果用户按住键。

    【讨论】:

      【解决方案4】:

      KeyPressEventHandler

      private void listView_KeyPress(object sender, KeyEventArgs e)
      

      必须改成

      private void listView_KeyPress(object sender, KeyPressEventArgs e)
      

      【讨论】:

      • KeyPressEventArgs 不包含 KeyCode
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      相关资源
      最近更新 更多