Search code examples
.netvb.netkeypresskeydown

VB toggle specific form with key press events


Hello I'm having difficulty showing a form when a specific set of keys are pressed. The main form runs first; this is a second form that’s supposed to be hidden until toggled by pressing ctrl+alt+shift+h. This is the code that I have, I believe it should work, but it is not. I tried it like this, in a timer that checks for the press events every 1 millisec

Private Sub tmrKeys_Tick(sender As Object, e As EventArgs) Handles tmrKeys.Tick
    Dim key As String = Nothing

    If My.Computer.Keyboard.AltKeyDown AndAlso My.Computer.Keyboard.CtrlKeyDown AndAlso My.Computer.Keyboard.ShiftKeyDown AndAlso key = "H" Then
        Dim x = New form2()
        x.Show()
    End If
End Sub

And I also tried a separate function like this:

Private Sub form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.Control AndAlso e.Alt AndAlso e.Shift AndAlso e.KeyCode = Keys.H Then
        form2.Show()
    End If
End Sub

Thank you in advance for the help.


Solution

  • This is what I was looking for. Thank you to @jmcilhinney for the hint towards RegisterHotKey on how to register active hotkeys. This code sets the hotkeys to alt+UPKEY. I want to figure out how to modify the parameters to assign more than 2 keys, like CTRL+ALT+SHIFT+UPKEY. But I have to head to work, so I’ll work on it tonight and update it tomorrow for everyone, unless an eager beaver wants to show me how to do this while I’m at work lol. Thanks again to everyone that helped!

    Public Class Form1
    
    Public Declare Function RegisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer
    Public Declare Function UnregisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer) As Integer
    Public Const WM_HOTKEY As Integer = &H312
    
    
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_HOTKEY Then
            Form2.Show()
        End If
    
        MyBase.WndProc(m)
    
    End Sub
    
    
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Call UnregisterHotKey(Me.Handle, 9)
    
    End Sub
    
    
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call RegisterHotKey(Me.Handle.ToInt32, 0, &H1, 38) '<-- registers specific hotkeys
    
    End Sub
    End Class