Implementing Keyboard Hook in VB.NET

Hello,

I have a VB.NET program that I need to execute code if a key combination is pressed (Ctrl+Shift+Alt+S). This code needs to be executed whether the program is in focus or not.
[Note: If anyone has used Deep Freeze, this is just exactly how that program functions - i.e. after you press a specific key combination the program's menu appears even if the program was not in focus]

In the course of my search for a solution I came across Windows Keyboard Hooks as the most likely candidate. My issue is that I can't get anything I try to work and I just really need help implementing this solution: what code should I use, advice about where to implement it in my program, etc.

So, Specifically, I have created a "Settings Page" in my program that, among other things, has a Checkbox for executing a forced shutdown command if Ctrl+Shift+Alt+S is pressed. [Note: The settings on the Form are saved in a Txt file and loaded both on Form Load and when the "Ok" or "Apply" buttons are pressed on that Settings Page.] I'd like the Ctrl+Alt+Shift+S key combination to become active only when the Checkbox for the feature is marked, and will initiate the forced shutdown regardless of whether my program is in focus or not.

Thank you in advance
MurrayHillITAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HaiFaiCommented:
Hi

You need to register hotkey, add this to your code

Imports System.Runtime.InteropServices

Public Class Form1
    Public Const MOD_ALT As Integer = &H1 + &H2 + &H4
    'H1 is MOD_ALT, H2 is MOD_CONTROL, H4 is MOD_SHIFT
    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(sender As Object, e As EventArgs) Handles MyBase.Load
        RegisterHotKey(Me.Handle, 100, MOD_ALT, Keys.Up)
        RegisterHotKey(Me.Handle, 200, MOD_ALT, Keys.Down)
        RegisterHotKey(Me.Handle, 300, MOD_ALT, Keys.Left)
        RegisterHotKey(Me.Handle, 400, MOD_ALT, Keys.Right)
        RegisterHotKey(Me.Handle, 500, MOD_ALT, Keys.S)
    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"
                    MsgBox("ctrl + alt + sift + up")
                Case "200"
                    MsgBox("ctrl + alt + sift + down")

                Case "300"
                    MsgBox("ctrl + alt + sift + left")
                Case "400"
                    MsgBox("ctrl + alt + sift + rigth")
                Case "500"
                    MsgBox("ctrl + alt + sift + s")
            End Select
        End If
        MyBase.WndProc(m)
    End Sub
End Class

Open in new window


i did put few examples up, down, rigth, left, s combos
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HaiFaiCommented:
I forgot to add windows key its
MOD_WIN
0x0008
so if you want to use that just add &H8 to this line
Public Const MOD_ALT As Integer = &H1 + &H2 + &H4

Open in new window


you can allso remove any combo of those keys

and remember to unregister keys after program close

UnregisterHotKey(Me.Handle, 100)
UnregisterHotKey(Me.Handle, 200)
'..etc...

Open in new window

0
MurrayHillITAuthor Commented:
Thanks! Just one more thing. How can I call this from another form? I'm having a little difficulty calling it from my Settings form (where the checkboxes for the specific settings are).
0
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

HaiFaiCommented:
Hi

Hotkey should work anywhere no matter what form is currently active, or what do you mean?
0
HaiFaiCommented:
oh did you mean like this

add this to main form
   Public checkedsetting As Boolean = False

Open in new window


change this
 Case "500"
                    If checkedsetting = True Then
                        MsgBox("cheked")
                    Else
                        MsgBox("not cheked")
                    End If

Open in new window


and in settings page you need to save state of checkbox to checkedsetting so add this settings form
  Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then
            Form1.checkedsetting = True
        Else
            Form1.checkedsetting = False
        End If
    End Sub

Open in new window


in settings page code you need to change "Form1" to point your main form
0
MurrayHillITAuthor Commented:
Why can't I just do this in my settings form:

If ShoprtcutCheckBox.Checked Then
     'Initiate Keyboard Hook
     Call Form1.ResgisterHotKey(Me.Handle, 100, Form1.MOD_ALT, Keys.S)
Else
     'Unregister Keyboard Hook
     Call Form1.UnregisterHotKey(Me.Handle, 100)
End If
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.