Search code examples
vb.netkeypresshotkeys

VB.Net Hidden Program Hotkeys


Is there a way to register hotkeys to toggle a form from an invisible(hidden) program? I’ve tired normal methods and they only work when the form is either visible, or the active window. Thank you in advance for any help!

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.KeyPreview = True
    Me.ShowInTaskbar = False
    Me.ShowIcon = False
    Me.Visible = False
End Sub

This is the code that hides the program.


Solution

  • You want to use Global Hotkeys. Just make sure you unregister when the program closes.

    From a MSDN article that helped me in the past:

    Firstly, you need to know the Virtual-Key Codes.

    http://msdn2.microsoft.com/en-us/library/ms927178.aspx You can then P/Invoke RegisterHotKey/UnregisterHotKey APIs to register/Unregister the hotkey. Code sample: Register multiple hotkeys such as Alt+D, Alt+C, etc.

    Imports System.Runtime.InteropServices
    
    Public Class Form1
    
        Public Const MOD_ALT As Integer = &H1 'Alt key
        Public Const WM_HOTKEY As Integer = &H312
    
        <DllImport("User32.dll")> _
        Public Shared Function RegisterHotKey(ByVal hwnd As IntPtr, _
                            ByVal id As Integer, ByVal fsModifiers As Integer, _
                            ByVal vk As Integer) As Integer
        End Function
    
        <DllImport("User32.dll")> _
        Public Shared Function UnregisterHotKey(ByVal hwnd As IntPtr, _
                            ByVal id As Integer) As Integer
        End Function
    
        Private Sub Form1_Load(ByVal sender As System.Object, _
                            ByVal e As System.EventArgs) Handles MyBase.Load
            RegisterHotKey(Me.Handle, 100, MOD_ALT, Keys.D)
            RegisterHotKey(Me.Handle, 200, MOD_ALT, Keys.C)
        End Sub
    
        Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
            If m.Msg = WM_HOTKEY Then
                Dim id As IntPtr = m.WParam
                Select Case (id.ToString)
                    Case "100"
                        MessageBox.Show("You pressed ALT+D key combination")
                    Case "200"
                        MessageBox.Show("You pressed ALT+C key combination")
                End Select
            End If
            MyBase.WndProc(m)
        End Sub
    
        Private Sub Form1_FormClosing(ByVal sender As System.Object, _
                            ByVal e As System.Windows.Forms.FormClosingEventArgs) _
                            Handles MyBase.FormClosing
            UnregisterHotKey(Me.Handle, 100)
            UnregisterHotKey(Me.Handle, 200)
        End Sub
    
    End Class