Apr 18
Monitoring Key Presses … The Lazy Way
So several of the applications I have written these last two weeks have involved monitoring the keyboard for key presses in one way or another. There are a couple of ways to go about this sort of thing, one easy way and one hard (but less resource intense). The first way is to loop (using a timer) checking the state of the keyboard every so often. The second way is to use a global keyboard hook, which is a little bit difficult to implement since you have to have an outside dll do some of the work.
So obviously I am going to show you the lazy easy way since that is what I have been using. The easy way is the only way to really do it when you are knocking out code quickly for small amusing apps.
Lets look at the code
Private Declare Function GetKeyState Lib "user32.dll" (ByVal virtKey As Short) As Short
Private Sub tmrMuahaha_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrMuahaha.Tick
'if a is down
If (GetKeyState(Keys.A) < 0) Then ' getKeyState Returns -1 if the key is down
doSomthingBecauseAIsDown()
End If
End Sub
I know what you are thinking, WOW that is easy. So basically all you need is a timer called tmrMuahaha on your form, set it to enabled and an interval of 100ms. Then whenever a key is pressed of your choice you can do something. That is really all there is to it.
The only other thing you might need is the Random class to help randomize when you do something. For example
Private Sub doSomethingBecauseAIsDown()
Dim rand As New Random
Dim i As Integer = rand.Next(100)
'This is a 30% chance
If (i < 30) Then
okSeriouslyDoSomthingNow()
End If
End Sub
Thats all for today folks, thanks for stopping by.