Question Catching Multiple Keystrokes

Fishbone

New member
Joined
Oct 7, 2008
Messages
2
Programming Experience
Beginner
Hi everyone

I'm trying to catch the following key combination......
Ctrl+Alt+Shift+M+U+L

Here is my code
VB.NET:
If e.KeyCode = Keys.M And Keys.U And Keys.L And (e.Control And e.Alt And e.shift) Then

'Code goes Here

End If

The event fires as soon as I press the M key after Ctrl Alt and Shift
I only want it to fire once all the keys have been pressed ie. M+U+L.

Is this possible?
 
The keyboard events doesn't work like that, and comparison operators doesn't work like that. The keyboard events are raised once for each key down/press/up, so you only get one piece of the puzzle each time. So you have to manage which keys are pressed down and up with some kind of collection and compare this with your target combination. Since Key down repeats when held you should only make the comparison once on keyup. Here's an example:
VB.NET:
Private keysdown As New List(Of Keys)

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
        Case Keys.ControlKey, Keys.ShiftKey, Keys.Menu
            'ignore these
        Case Else
            If Not keysdown.Contains(e.KeyCode) Then
                keysdown.Add(e.KeyCode)
            End If
    End Select
End Sub

Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
    If e.Control AndAlso e.Shift AndAlso e.Alt AndAlso IsKeysCombination(New Keys() {Keys.M, Keys.U, Keys.L}) Then
        MsgBox("ctrl+shift+alt+m+u+l")
    End If
    keysdown.Remove(e.KeyCode)
End Sub

Private Function IsKeysCombination(ByVal keys() As Keys) As Boolean
    If keysdown.Count <> keys.Length Then Return False
    For Each key As Keys In keys
        If Not keysdown.Contains(key) Then Return False
    Next
    Return True
End Function
The example uses the Forms keyboard events, which requires KeyPreview set to True.
 
Hi JohnH
Thanks is works a treat.
Didn't realise it would require quite as much code to perform this task.
Thanks again for the help. I really appreciate it.
 
Back
Top