Solved

Keyboard Hook issues

Posted on 2006-06-24
15
1,853 Views
Last Modified: 2012-06-27
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
Comment
Question by:MikeSel
  • 5
  • 4
  • 3
  • +2
15 Comments
 
LVL 9

Expert Comment

by:jrscherer
ID: 16977575
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
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 16979069
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
 
LVL 4

Author Comment

by:MikeSel
ID: 16980237
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 16980351
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16980738
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 16980770
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16980809
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 4

Author Comment

by:MikeSel
ID: 16982397
Thanks everyone for your help! Running it as a compiled exe does work..

:-)

Sorry I couldnt 'split' the points with you Idle_Mind
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 16984146
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 16985851
No points necessary...glad to help out.  =)
0
 
LVL 14

Expert Comment

by:jake072
ID: 26009488
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 26009502
Thanx for posting Jake.  =)
0
 
LVL 14

Expert Comment

by:jake072
ID: 26010794
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 26010804
It also affects VS2008 so I'm sure you're comment will be helpful for quite awhile...  =)
0
 
LVL 14

Expert Comment

by:jake072
ID: 26010844
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now