Link to home
Start Free TrialLog in
Avatar of MikeSel
MikeSelFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Keyboard Hook issues

Hello all..

I am trying to capture an block some keyboard presses..

I have the following code, which I got from another website, but can I hell as like get it to work!!


Imports System.Runtime.InteropServices
Imports System.Reflection
Imports System.Drawing
Imports System.Threading

Module Keyboard
    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 LLKHF_INJECTED As Integer = &H10
    Private Const LLKHF_ALTDOWN As Integer = &H20
    Private Const LLKHF_UP As Integer = &H80

    ' Virtual Keys
    Public Const VK_TAB = &H9
    Public Const VK_CONTROL = &H11
    Public Const VK_ESCAPE = &H1B
    Public Const VK_DELETE = &H2E

    Private Const WH_KEYBOARD_LL As Integer = 13&
    Public KeyboardHandle As Integer


    ' Implement this function to block as many
    ' key combinations as you'd like
    Public Function IsHooked( _
      ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean

        Debug.WriteLine("Hookstruct.vkCode: " & Hookstruct.vkCode)
        Debug.WriteLine(Hookstruct.vkCode = VK_ESCAPE)
        Debug.WriteLine(Hookstruct.vkCode = VK_TAB)

        If (Hookstruct.vkCode = VK_ESCAPE) And _
          CBool(GetAsyncKeyState(VK_CONTROL) _
          And &H8000) Then

            Call HookedState("Ctrl + Esc blocked")
            Return True
        End If

        If (Hookstruct.vkCode = VK_TAB) And _
          CBool(Hookstruct.flags And _
          LLKHF_ALTDOWN) Then

            Call HookedState("Alt + Tab blockd")
            Return True
        End If

        If (Hookstruct.vkCode = VK_ESCAPE) And _
          CBool(Hookstruct.flags And _
            LLKHF_ALTDOWN) Then

            Call HookedState("Alt + Escape blocked")
            Return True
        End If

        Return False
    End Function

    Private Sub HookedState(ByVal Text As String)
        Debug.WriteLine(Text)
    End Sub

    Public Function KeyboardCallback(ByVal Code As Integer, _
      ByVal wParam As Integer, _
      ByRef lParam As KBDLLHOOKSTRUCT) As Integer

        If (Code = HC_ACTION) Then
            Debug.WriteLine("Calling IsHooked")

            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 (Hooked()) Then
            Debug.WriteLine("Keyboard hooked")
        Else
            Debug.WriteLine("Keyboard hook failed: " & Err.LastDllError & " " & Err.Description)
        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



When I call it from my form using      Keyboard.HookKeyboard()

I get an error in the output window
Keyboard hook failed: 0
Keyboard hook failed: 1008

Any ideas?

Or another way to do it!?
Avatar of jrscherer
jrscherer
Flag of United States of America image

I did try similar hooks on Win XP SP2. Could not make it work. I was told that WinXP has some security feature which rejects keyboard hooks. I gave up and bought a commercial product. (I wonder how they do it)
Maybe I am wrong and there is a way, but I spent too much time with no result.
Jack.net
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MikeSel

ASKER

Thanks guys, I downloaded the code, and it still the same issue :(
I'm wondering if it's my version of visual studio..

It's 2005, should be the full comercial release but it was a microsoft developer pack.

I had a code conversation confirmation when I tried to run the code above..
It seems to be VB .Net 2005. I tried it in 2005 and the windows hook dll fails but when I try it in VB .Net 2003 it woeks fine. I will see if I can find out why.
Hi guys...I have had the same problem before.

In VB.Net 2005, the keyboard hook only works in the actual compiled EXE.  It does NOT work in the IDE...
Thank you very much Idle_Mind you are correct I tryed it out side the IDE running the exe and it worked just fine but in the IDE it does not work. Well that's Microsoft for you. :=)

Fernando
I never did find out what the difference is...

Spent alot of time fiddlilng with code just to find out the original code was just fine!

Grrrrrrrrrrrr.........   =\
Avatar of MikeSel

ASKER

Thanks everyone for your help! Running it as a compiled exe does work..

:-)

Sorry I couldnt 'split' the points with you Idle_Mind
Hi  MikeSel;

You can place a zero point question in the community support to have the question re-opened so that you can give Idle_Mind some credit for the answer.

Have a Great day;

Fernando
No points necessary...glad to help out.  =)
I know this thread is old, but anyone interested in getting it to work in the IDE (i.e., in debug mode), I have a solution.

The problem is that the exe is run via vshost, which disrupts the hinst callback retrieval.

Code attached; change the line in the HookKeyboard Sub...  Note I implemented this in a Class.

Jake
KeyboardHandle = SetWindowsHookEx(WH_KEYBOARD_LL, callback, GetWindowLong(Me.Handle, GWL_HINSTANCE), 0)

Open in new window

Thanx for posting Jake.  =)
Idle_Mind,

My pleasure.  I was going insane with this issue, and thought it would be useful to others...  I hadn't even considered that it was a debugging issue until I came here, and I had a feeling it could be fixed!  NOTE: This is only affected (as mentioned) in VS 2005+, although, I'm sure these days not many people are running VS 2003- =)

Jake
It also affects VS2008 so I'm sure you're comment will be helpful for quite awhile...  =)
Correct, and I believe it will affect 2010 as well (I have the beta installed in 1 of my VMs =)), unless it's some weird VM issue, but I'm fairly certain it's just the way VS debugging is implemented with the new Vista/7 security, so, going forward, I hope it helps people!

Jake