Detect if keys are being held down
Posted: Mon Mar 14, 2011 10:05 pm
How can i detect if say
w is being held in and when it is released show a message box ?
w is being held in and when it is released show a message box ?
Sharing, Teaching and Supporting coders of all ages and levels since 2009
https://www.codenstuff.com/forum/
<DllImport("user32.dll")> Shared Function GetAsyncKeyState(ByVal vKey As Integer) As Short
End Function
Dim isDown As Boolean = False
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim res As Short = GetAsyncKeyState(Keys.W)
If res = -32767 Then
isDown = True
ElseIf res = 0 And isDown Then
Timer1.Stop()
MsgBox("W released")
End If
End Sub
Public WDown As Boolean = False
Public OtherDown As Boolean = False
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.W Then
WDown = True
Else
OtherDown = True
End If
End Sub
Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If WDown = True Then
WDown = False
MsgBox("W released")
Else
OtherDown = False
MsgBox("Other key released")
End If
End Sub
GoodGuy17 wrote:Couldn't the same goal be achieved using:I suppose he is trying to develop a keyboard hook, a keyboard hook is system wide instead of just on a form, your code only works on a specific form, using mandai's code(Asynckeys), you're able to detect keys being pressed system wide, therefore, I recommend him using mandai's code.
Code: Select allPublic WDown As Boolean = False Public OtherDown As Boolean = False Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown If e.KeyCode = Keys.W Then WDown = True Else OtherDown = True End If End Sub Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp If WDown = True Then WDown = False MsgBox("W released") Else OtherDown = False MsgBox("Other key released") End If End Sub