Check if DELETE key is pressed?

26,605

Solution 1

The KeyEventArgs object contains a member called "KeyCode" that you can compare to the "Keys" enumeration.

Note that certain keys may not raise the KeyDown event if they are handled by the default windowing system. I'm not sure, and I can't check it right now, but you may not get the KeyDown event for keys like Tab, Delete, Enter, etc.

You can usually do something like this (this is C#, not VB, but should be similar):

public void MyControl_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        // delete was pressed
    }
}

Solution 2

If you set KeyPreview property of form then form will receive key events before the event is passed to the control that has focus. For example if you have textboxes and buttons on the form, normally they(the control that has focus) will capture the key press event. So make sure to set KeyPreview=true

Use this to capture the key code.

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Delete Then
        'todo
    End If
End Sub

Solution 3

Compare e.keyValue with Keys.Delete

Solution 4

Check the Keys enumeration...

Share:
26,605
Saturn
Author by

Saturn

Updated on September 24, 2020

Comments

  • Saturn
    Saturn over 3 years
    Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
    

    What is the keyValue I need for checking for the DELETE key using e.keyValue?