Domanda

I add a key press event

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

The framework automatically creates the class for it:

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

When compiling I get an error on System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress)

No overload for 'listView_KeyPress' matches delegate 'System.Windows.Forms.KeyPressEventHandler'    D:\...\MainForm.Designer.cs

I would appreciate any helpful answer, thanks.

È stato utile?

Soluzione

The KeyPress event needs the parameter KeyPressEventArgs instead of KeyEventArgs.

However the KeyPress event only gives you the character of the key you pressed. And the DELETE key has no character. Therefor you should use the event KeyDown instead, as this one is gives you the KeyCode instead:

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

Altri suggerimenti

Your signature is wrong. The e parameter in your handler shoudl be KeyPressEventArgs not KeyEventArgs

The KeyPressEventHandler delegate expects the second parameter to be a KeyPressEventArgs object, not KeyEventArgs:

private void listView_KeyPress(object sender, KeyPressEventArgs e)

If you need to use information found in KeyEventArgs, you should instead use the KeyDown event. If so, be aware that the KeyDown event can be raised several times, if the user keeps the key pressed.

See KeyPressEventHandler

private void listView_KeyPress(object sender, KeyEventArgs e)

has to be changed to

private void listView_KeyPress(object sender, KeyPressEventArgs e)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top