Search code examples
.netvb.netkeyboardapplication-start

get keydown on application/form load in vb.net


I want to able to hold a key down while the application is loading and depending on which is being held down a certain form is shown.

For example holding down shift and the opening itunes opens a little dialog allowing you set the library(or something)

I can check whether the shift/Ctrl/Alt are being held down but i'd prefer to use the letters/digits.

Such as hold 1 down to open Form1 and hold 2 down to open form 2.


Solution

  • If you're wanting to do this on traditional winforms, you can check out this article:

    http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state

    About half-way down there's an abstract Keyboard class that uses a system call to get key states. You might want to give it a try.

    EDIT: Here's that class converted to VB.NET. I haven't tested it so there might be some errors. Let me know.

    Imports System
    Imports System.Windows.Forms
    Imports System.Runtime.InteropServices
    
    Public MustInherit Class Keyboard
    
        <Flags()>
        Private Enum KeyStates
            None = 0
            Down = 1
            Toggled = 2
        End Enum
    
        <DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True)>
        Private Shared Function GetKeyState(ByVal keyCode As Integer) As Short
        End Function
    
        Private Shared Function GetKeyState(ByVal key As Keys) As KeyStates
            Dim state = KeyStates.None
    
            Dim retVal = GetKeyState(CType(key, Integer))
    
            ' if the high-order bit is 1, the key is down
            ' otherwise, it is up
            If retVal And &H8000 = &H8000 Then
                state = state Or KeyStates.Down
            End If
    
            ' If the low-order bit is 1, the key is toggled.
            If retVal And 1 = 1 Then
                state = state Or KeyStates.Toggled
            End If
    
            Return state
        End Function
    
        Public Shared Function IsKeyDown(ByVal key As Keys) As Boolean
            Return KeyStates.Down = (GetKeyState(key) And KeyStates.Down)
        End Function
    
        Public Shared Function IsKeyToggled(ByVal key As Keys) As Boolean
            Return KeyStates.Toggled = (GetKeyState(key) And KeyStates.Toggled)
        End Function
    
    End Class
    

    So once you add this class to your project, you can do something like this:

    ' See if the 1 button is being held down
    If Keyboard.IsKeyDown(Keys.D1) Then
        ' Do the form showing stuff here
    EndIf