Levi Levi - 1 year ago 123
Vb.net Question

VB.net Key Combinations doesn't work

The following code works for Ctrl + D, F2, and F7, but does not work for Ctrl + A. Anyone know where my issue is at? Thanks in advance!!!

Private Sub AgentSetupForm_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyCode
' Ctrl + A
Case Keys.A And (e.Control And Not e.Shift And Not e.Alt)
Dim f As New InvestorAccountsForm
f.MdiParent = TraderoomMDI

' Ctrl + D
Case Keys.D And (e.Control And Not e.Shift And Not e.Alt)
Dim f As New InvestorAddressForm
f.MdiParent = TraderoomMDI
' F2, F7
Case Keys.F2 'And (e.Shift And Not e.Control And Not e.Alt)
Me.Text = "F2 Test"
Case Keys.F7
stlFormMode.Text = "Edit"
End Select

End Sub

Answer Source


Keys.A And (e.Control And Not e.Shift And Not e.Alt)

you are using the bitwise And (instead of the logical And) due to that your Select Case-statement is checking for an Integer (e.KeyCode). This means that when you press CTRL + A your first case will be checking for:

65 And (1 And Not 1 And Not 1) = 65 And (1 And 0 And 0) = 0

Your first case will return 0, but e.KeyCode when pressing A will be 65.

It's a bit complicated to check multiple statements in a Case-statement. To be able to do it your Select Case must check for a Boolean instead:

Select Case True
    Case e.KeyCode = Keys.A AndAlso (e.Control AndAlso Not e.Shift AndAlso Not e.Alt)
        'Using AndAlso since it performs shortcircuiting, thus it's faster.

    ...rest of your cases here...
End Select

Due to that you must now add e.KeyCode = ... in your Case, you might aswell use a normal If-statement instead:

If e.KeyCode = Keys.A AndAlso (e.Control AndAlso Not e.Shift AndAlso Not e.Alt) Then
ElseIf ... Then
End If


As it seems you have an issue with the CTRL + A combination, you could try overriding ProcessCmdKey and see if that works. The method should be called before the keys are handled and/or translated by the .NET environment.

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = (Keys.Control Or Keys.A) Then
        ...your code here...
        Return True
    End If

    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

If the other combinations work you can keep them in the KeyDown event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download