?
Solved

Keyboard Hook issues

Posted on 2006-06-24
15
Medium Priority
?
1,860 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 64

Accepted Solution

by:
Fernando Soto earned 2000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 64

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 86

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 64

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 86

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
 
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 64

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 86

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 86

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 86

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

649 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