Solitaire
Well-known member
I am updating a program I wrote to display key codes when a key is pressed. The problem is that when the Alt-Esc key combination is pressed, the form hides behind the window. When the Ctrl-Esc key combination is pressed, the Start menu opens. How can these side effects be avoided?
Here is my code. Only 2 labels are on the form:
Here is my code. Only 2 labels are on the form:
VB.NET:
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
'Form must have focus. No visible user controls except labels may be on the form.
'Form's KeyPreview property was set to True 'or add KeyPreview = True in the Form Load event
Dim msg As String = e.KeyData.ToString & " was pressed."
msg &= " KeyValue = " & e.KeyValue.ToString
lblKeyCode.Text = msg
e.SuppressKeyPress = True 'Prevents Alt beep from sounding
'If e.KeyValue = 17 Then e.Handled = True 'same as: If e.KeyCode = Keys.Control 'doesn't work
'Ctrl-Esc will open the Menu and possibly freeze keypresses. Click form to reset and continue.
'If e.KeyValue = 18 Then e.Handled = True 'same as: If e.KeyCode = Keys.Alt 'doesn't work
'Alt-Esc will hide the form behind the window. Click form to reset and continue.
Select Case e.KeyValue
Case 112 To 123 'all the F keys; prevent 11-12 or 1-10 from freezing
e.Handled = True 'If cursor key pressed after F key, will focus on a control even if TabStop is False
End Select
lblASCII.Text = "ASCII Value: (not available)" 'clears Label2 if ASCII code cannot be displayed
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
Dim askey As Integer
askey = Asc(e.KeyChar)
lblASCII.Text = "ASCII code for the " & e.KeyChar & " key is " & askey
'Label is cleared first by KeyDown.
'This Keypress event is not triggered if a non-ASCII key is pressed.
'e.Keycode not available in Keypress event. e.KeyChar not available in KeyDown event.
End Sub
Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
lblKeyCode.Text = "Press any key"
lblASCII.Text = "ASCII value"
End Sub