press/release key

craypen

Member
Joined
May 13, 2009
Messages
10
Programming Experience
Beginner
if i have one button

the i want this button event press f9 and hold it

and i have buuton2

the event release f9

how can i wite it ?

:)
 
Very hard to read, are you wanting F9 key down to Button1.PreformClick and F9 keyup to Button2.PerformClick()? If so use the Form's Key Down and then the KeyUp Events with the code I already showed.
 
The form must have the focus in order for any keypresses to take effect. You must set the Tab Index to False on any controls that are on the form. Label controls do not have a Tab Index.

The KeyValue of the F9 key is 120. The following code will work if you press the F9 key, hold it down, and then release it. It calls on the buttons' PerformClick events. Any code you place behind the buttons will then execute. The following demo shows how it works. It will change the text on the label to show that the key was pressed or released.

However, if you have a lot of controls on your form that require Tab stops, then you may want to rethink how you want to design your project.


Note: Place 2 buttons and a label on a new form to try out this demo code. The Buttons must have the Tab Stop property set to False.


VB.NET:
	Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
		If e.KeyValue = 120 Then
			Button1.PerformClick()
		End If
	End Sub

	Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
		If e.KeyValue = 120 Then
			Button2.PerformClick()
		End If
	End Sub

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Label1.Text = "F9 was pressed."
	End Sub

	Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
		Label1.Text = "F9 was released."
	End Sub
 
Last edited:
Solitaire said:
The KeyValue of the F9 key is 120.
The Keys value of F9 key is Keys.F9.
VB.NET:
If e.KeyCode = Keys.F9 Then
Though I think OP means opposite.
 
Yes, the If e.KeyCode = Keys.F9 is a lot clearer.

However, I found another problem. As soon as one of the buttons is clicked, it now has the focus and the F9 keypress will no longer work. I tried adding Me.Focus() at the end of the button codes, but that didn't work.

So, unless someone else comes up with a way to have a keypress recognized at any time during a program run, it looks like this proposed solution is a bad idea and you will have to find another way to design your program.
 
Back
Top