• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1861
  • Last Modified:

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!?
0
MikeSel
Asked:
MikeSel
  • 5
  • 4
  • 3
  • +2
1 Solution
 
jrschererCommented:
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
0
 
Fernando SotoCommented:
Hi MikeSel;

I ran accross the same program on a question some time ago and got it to work for them. I have uploaded the project file which is basically what you have posted with a form to Hook and unhook the keyboard. The code as is will block the following keys. Control + Escape, Alt + Tab and Alt + Escape. Others can be add or removed as needed. I have run this on a Windows XP Pro and SP2 with no problem

Link to download the working project file.

        https://filedb.experts-exchange.com/incoming/ee-stuff/263-LowLevelKeyboardHooks.zip

Fernando
0
 
MikeSelAuthor Commented:
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..
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Fernando SotoCommented:
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.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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...
0
 
Fernando SotoCommented:
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
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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.........   =\
0
 
MikeSelAuthor Commented:
Thanks everyone for your help! Running it as a compiled exe does work..

:-)

Sorry I couldnt 'split' the points with you Idle_Mind
0
 
Fernando SotoCommented:
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
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
No points necessary...glad to help out.  =)
0
 
jake072Commented:
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

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Thanx for posting Jake.  =)
0
 
jake072Commented:
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
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
It also affects VS2008 so I'm sure you're comment will be helpful for quite awhile...  =)
0
 
jake072Commented:
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
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 5
  • 4
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now