Detect if keys are being held down
Do you need something made? then ask in here.
Forum rules
Please LOCK your topics once you have found the solution to your question so we know you no longer require help with your query.
Please LOCK your topics once you have found the solution to your question so we know you no longer require help with your query.
6 posts
Page 1 of 1
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 ?
Nailing my feet to the floor is easier than using my own muscles to balance, but you don't see me doing that 

Most controls have the MouseUp event. Just go to Code View, in the top left combobox, choose your control, in the top right, choose MouseUp.
You can't use mouse events to detect key states. Use GetAsyncKeyState to check for that.
Code: Select all
<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
Couldn't the same goal be achieved using:
Code: Select all
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
Ill try it later thanks for replying mandai and reboh
Nailing my feet to the floor is easier than using my own muscles to balance, but you don't see me doing that 

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
6 posts
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023