Question Keypress event problem

ucp8

Active member
Joined
Feb 9, 2009
Messages
28
Programming Experience
3-5
Hi,

I have created the following piece of code to try and see if the user pushes the 'f1' key, and if they do, a help box will open.

VB.NET:
[SIZE="2"]Private Sub LoginForm_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        ' If F1 key is pressed open help form
        If (e.KeyChar.Equals(Keys.F1)) Then
            ' If 'Help' is clicked, show help form
            Dim newLoginHelp As New LoginHelpForm
            newLoginHelp.Show()
        End If
End Sub[/SIZE]

I am not sure if this code works yet because the keypressed event is not triggered when I push a key.

Could someone tell me how I can change my code so that it will test what key is pressed, no matter what control on the form has focus?

Thanks for your help
 
The following will work in the Form's KeyDown event. It will give you the keycodes for any key you press.


VB.NET:
	Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
		Dim mykey As String, mydata As Object
		mykey = Chr(e.KeyCode)
		mydata = e.KeyData
		Label1.Text = mykey & " was pressed.  The code for the  " & mydata.ToString & "  key is " & e.KeyCode
		
		If mykey = Chr(112) Then
			MessageBox.Show("F1 key was pressed")
		End If
	End Sub
 
Thanks for the help Solitaire.

Unfortunately it didn't work for me. It seems that the key events are not being triggered at all in my code.

Any ideas why?
 
It works perfectly for me. I started with a new project and a blank form.

Did you use the KeyDown event? It won't work with the KeyPress event, which can only handle ASCII characters. The F keys need special keycodes, which are only accessible through the KeyDown event.
 
KeyDown (and KeyUp) dont seem to work with forms that have controls on them, unless the KeyPreview property of a form is set to True. KeyDown should then be fine :D
 
I used the keyDown event as you said. Setting the KeyPreview property to True fixed the problem and allowed the key events to trigger.


Thanks for all you help guys. It's most appreciated! :)
 
If you want to prevent the handler code to run multiple times for keypresses (accidentally) use the KeyUp event instead, because KeyDown repeats while the key is held downnnnnnnn.
 
Back
Top