Results 1 to 10 of 10

Thread: [RESOLVED] Keyboard Hook

  1. #1

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Resolved [RESOLVED] Keyboard Hook

    I'm trying to set a hook so that I can respond to a key combo such as Ctrl+O, without having the app in focus.

    I've tried the registerhook method but it's not comlpetely global, say if I have a game running the event is not fired when the combo is pressed.

    I've looked at DirectInput which worked in VB6 but haven't found a good .net sample.

    BTW it's VB2005

    Cheers
    Last edited by the182guy; May 12th, 2007 at 07:48 AM.
    Chris

  2. #2
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148

    Re: Keyboard Hook

    For a single key combination a system wide hotkey (as per this component) is probably your best bet.

    Under the hood it uses the API call RegisterHotkey...

  3. #3

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Keyboard Hook

    Yeah I've tried it mate, it's not truely system wide as it doesn't function when running a game.
    Chris

  4. #4
    PowerPoster
    Join Date
    Jul 2002
    Location
    Dublin, Ireland
    Posts
    2,148

    Re: Keyboard Hook

    If a game is written using DirectInput (as most are) then nothing will hook it...sorry to be the bringer of bad news.

  5. #5
    Frenzied Member bmahler's Avatar
    Join Date
    Oct 2005
    Location
    Somewhere just west of the Atlantic
    Posts
    1,568

    Re: Keyboard Hook

    You can actually use a low level keyboard hook to get underneath di. This is a class that i use for the purpose of hooking keys for games that I play. And yes, they all use DI. My IsHooked function has some stuff very specific to my uses, so you will have to change it for your needs, but I think this will work for you.
    Code:
    Imports System.Runtime.InteropServices
    Imports System.Reflection
    Module keyHook
    
        Public Declare Function UnhookWindowsHookEx Lib "user32" _
          (ByVal hHook As Integer) As Integer
    
        Public Declare Function SetWindowsHookEx Lib "user32" _
          Alias "SetWindowsHookExA" (ByVal idHook As Integer, _
          ByVal lpfn As KeyboardHookDelegate, ByVal hmod As Integer, _
          ByVal dwThreadId As Integer) As Integer
    
        Private Declare Function GetAsyncKeyState Lib "user32" _
          (ByVal vKey As Integer) As Integer
    
        Private Declare Function CallNextHookEx Lib "user32" _
          (ByVal hHook As Integer, _
          ByVal nCode As Integer, _
          ByVal wParam As Integer, _
          ByVal lParam As KBDLLHOOKSTRUCT) As Integer
    
        Public Structure KBDLLHOOKSTRUCT
            Public vkCode As Integer
            Public scanCode As Integer
            Public flags As Integer
            Public time As Integer
            Public dwExtraInfo As Integer
        End Structure
    
        ' Low-Level Keyboard Constants
        Private Const HC_ACTION As Integer = 0
        Private Const LLKHF_EXTENDED As Integer = &H1
        Private Const MOD_CONTROL As Long = &H2
        Private Const LLKHF_INJECTED As Integer = &H10
        Private Const LLKHF_ALTDOWN As Integer = &H20
        Private Const LLKHF_UP As Integer = &H80
        Private Const LLKHF_DOWN As Integer = &H81
    
    
        Public Const VK_CONTROL = &H11  'Control
        Public Const VK_PRIOR = &H21    'PAGE UP key
        Public Const VK_NEXT = &H22     'Page DOWN key
    
        Private Const WH_KEYBOARD_LL As Integer = 13&
        Public KeyboardHandle As Integer
    
    
        Public Function IsHooked(ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean
    
            Dim keyA, KeyC, KeyQ As Integer
            Dim ini As New IniFile(Application.StartupPath & "\Settings.ini")
            keyA = ini.GetString("KEYS", "Main", 65)
            KeyC = ini.GetString("KEYS", "Comment", 67)
            KeyQ = ini.GetString("KEYS", "Quest", 81)
            frmMain.MinimizeToTrayToolStripMenuItem.Text = "Minimize to Tray (ALT + " & CType(keyA, Keys).ToString
            frmMain.cWind.Text = "Toggle Comments Window (ALT + " & CType(KeyC, Keys).ToString
            frmMain.qWind.Text = "Toggle Quests Window (ALT + " & CType(KeyQ, Keys).ToString
    
            'Toggle the Main Window
            If (Hookstruct.vkCode = keyA) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) _
                And CBool(Hookstruct.flags And LLKHF_UP) Then
                If Not frmMain.Visible Then
                    frmMain.Show()
                    frmMain.BringToFront()
                Else
                    frmMain.Hide()
                End If
                Return True
            ElseIf (Hookstruct.vkCode = keyA) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) Then
                Return True
            End If
    
            'Toggle the Comments Window
            If (Hookstruct.vkCode = KeyC) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) _
                And CBool(Hookstruct.flags And LLKHF_UP) Then
                If Not frmComments.Visible Then
                    frmComments.Width = cWidth
                    frmComments.Height = cHeight
                    frmComments.Left = cWindowX
                    frmComments.Top = cWindowY
                    If cGlass Then
                        frmComments.TransparencyKey = Color.Black
                    Else
                        frmComments.Opacity = cTrans / 100
                    End If
                    frmComments.Show()
                Else
                    frmComments.Dispose()
                End If
                Return True
            ElseIf (Hookstruct.vkCode = KeyC) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) Then
                Return True
            End If
    
            'Toggle the Quests Window
            If (Hookstruct.vkCode = KeyQ) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) _
            And CBool(Hookstruct.flags And LLKHF_UP) Then
                If Not frmQuestInfo.Visible Then
                    frmQuestInfo.Width = qWidth
                    frmQuestInfo.Height = qHeight
                    frmQuestInfo.Left = qWindowX
                    frmQuestInfo.Top = qWindowY
                    If cGlass Then
                        frmQuestInfo.TransparencyKey = Color.Black
                    Else
                        frmQuestInfo.Opacity = qTrans / 100
                    End If
                    frmQuestInfo.Show()
                Else
                    frmQuestInfo.Dispose()
                End If
                Return True
            ElseIf (Hookstruct.vkCode = KeyQ) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) Then
                Return True
            End If
                Return False
        End Function
    
        Private Sub HookedState(ByVal Text As String)
    
        End Sub
    
        Public Function KeyboardCallback(ByVal Code As Integer, _
          ByVal wParam As Integer, _
          ByRef lParam As KBDLLHOOKSTRUCT) As Integer
            If (Code = HC_ACTION) Then
                If (IsHooked(lParam)) Then
                    Return 1
                End If
            End If
            Return CallNextHookEx(KeyboardHandle, _
              Code, wParam, lParam)
        End Function
    
    
        Public Delegate Function KeyboardHookDelegate( _
          ByVal Code As Integer, _
          ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) _
                       As Integer
    
        <MarshalAs(UnmanagedType.FunctionPtr)> _
        Private callback As KeyboardHookDelegate
    
        Public Sub HookKeyboard()
            callback = New KeyboardHookDelegate(AddressOf KeyboardCallback)
    
            KeyboardHandle = SetWindowsHookEx( _
              WH_KEYBOARD_LL, callback, _
              Marshal.GetHINSTANCE( _
              [Assembly].GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
    
            Call CheckHooked()
        End Sub
    
        Public Sub CheckHooked()
            If Not (Hooked()) Then
                MsgBox("Keyboard hook failed: " & Err.LastDllError)
            End If
        End Sub
    
        Private Function Hooked()
            Hooked = KeyboardHandle <> 0
        End Function
    
        Public Sub UnhookKeyboard()
            If (Hooked()) Then
                Call UnhookWindowsHookEx(KeyboardHandle)
            End If
        End Sub
    
    End Module
    Just a side note, this does not work in the ide, you must compile your project and run it for the hook to properly work. Not really sure why this happens, but it does.
    Boooya
    • Visual Studio 2008 Professional
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • Don't forget to rate helpful posts!
    • If you're question was answered please mark your thread [Resolved]


    Code Contributions:
    PHP
    PHP Image Gallery v1.0PHP Image Gallery v2.0
    VB 2005
    Find Computers on a networkSimple License EncryptionSQL Server Database Access dllUse Reflection to Return Crystal ReportDocumentSilently Print PDFGeneric Xml Serailizer


    Useful Links: (more to come)
    MSDN (The first and foremost)MSDN Design Guidelines API Reference • Inno Setup CompilerInno Setup PreprocessorISTool - Fairly easy to use GUI for creating inno setup projects • Connection StringsNAnt -Automated BuildsCruise Control .NET - Frontend for automated builds

  6. #6
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Keyboard Hook

    yeah there is always SOME underlying method to be global.. otherwise those game comm apps like teamspeak and vent wouldn't work when you were playing Dx games...

  7. #7

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Keyboard Hook

    Cheers lads I'll give that class a try. Yeah like I said before, I've had it working with DI through VB6 but haven't come across a decent .net sample till now.
    Chris

  8. #8

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Keyboard Hook

    The code is giving me the "hook failed" error when I call HookKeyboard(). I commented your stuff out, and just inserted a msgbox to test it.

    Also... how do I hook key A from example, as when you get the keycode your getting it from your ini file, is it ASCII codes?
    Chris

  9. #9
    Frenzied Member bmahler's Avatar
    Join Date
    Oct 2005
    Location
    Somewhere just west of the Atlantic
    Posts
    1,568

    Re: Keyboard Hook

    Quote Originally Posted by the182guy
    The code is giving me the "hook failed" error when I call HookKeyboard(). I commented your stuff out, and just inserted a msgbox to test it.

    Also... how do I hook key A from example, as when you get the keycode your getting it from your ini file, is it ASCII codes?
    It is Virtual Keys, just use the Keys enum. like so
    Code:
    If (Hookstruct.vkCode = Keys.A) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) _
        And CBool(Hookstruct.flags And LLKHF_UP) Then
        'Do something
        Return True
    ElseIf (Hookstruct.vkCode = Keys.A) And CBool(Hookstruct.flags And LLKHF_ALTDOWN) Then
        Return True
    End If
    Also about it saying the hook failed, did you read the part in my post that said this does not work when run from the ide. You need ot compile the project and run the executable to test it. When run from the IDE you will always get a hook failed error.
    Last edited by bmahler; May 11th, 2007 at 03:33 PM.
    Boooya
    • Visual Studio 2008 Professional
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • Don't forget to rate helpful posts!
    • If you're question was answered please mark your thread [Resolved]


    Code Contributions:
    PHP
    PHP Image Gallery v1.0PHP Image Gallery v2.0
    VB 2005
    Find Computers on a networkSimple License EncryptionSQL Server Database Access dllUse Reflection to Return Crystal ReportDocumentSilently Print PDFGeneric Xml Serailizer


    Useful Links: (more to come)
    MSDN (The first and foremost)MSDN Design Guidelines API Reference • Inno Setup CompilerInno Setup PreprocessorISTool - Fairly easy to use GUI for creating inno setup projects • Connection StringsNAnt -Automated BuildsCruise Control .NET - Frontend for automated builds

  10. #10

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Keyboard Hook - NOT RESOLVED!!

    Works 100%. Cheers mate, exactly what I needed.

    Edit: I can't rate you again yet, I will when I can mate.
    Chris

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width