SetWindowsHookEx returning 0

I'm trying to set a keyboard hook on another window, I just need to detect if the user pressed ctrl or alt
so:

Enum HookType

WH_JOURNALRECORD = 0

WH_JOURNALPLAYBACK = 1

WH_KEYBOARD = 2

WH_GETMESSAGE = 3

WH_CALLWNDPROC = 4

WH_CBT = 5

WH_SYSMSGFILTER = 6

WH_MOUSE = 7

WH_HARDWARE = 8

WH_DEBUG = 9

WH_SHELL = 10

WH_FOREGROUNDIDLE = 11

WH_CALLWNDPROCRET = 12

WH_KEYBOARD_LL = 13

WH_MOUSE_LL = 14

End Enum


Public Declare Function SetWindowsHookEx Lib "user32" Alias SetWindowsHookExA" (ByVal idHook As HookType, ByVal lpfn As HookProc, ByVal mod As IntPtr, ByVal dwThreadId As Long) As IntPtr

Delegate Function HookProc(ByVal code As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer

Public Function KeyboardProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer

hHook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, AddressOf KeyboardProc, WinWnd, 0)


but it is always returning zero, plusthe global variable for last error is set to 127

thanks in advance
marcel




Answer this question

SetWindowsHookEx returning 0

  • nsrajesh

    punk,

    Error 127 is procedure not found which is probably because the method cannot locate the callback for the hook. The following is straight from the msdn library:

    hMod
    [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.


    So with that said, in regular VB you would need to pass App.hInstance, in .NET you need to do similar. Change the Declaration to the following:



    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 HookProc, ByVal hMod As Integer, ByVal dwThreadId As Integer) As Integer

     


    Now to call this properly you can use:



    hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, New HookProc(AddressOf callback), Marshal.GetHINSTANCE([Assembly].GetExecutingAssembly.GetModules()(0)).ToInt32, 0)

     


    Then when finished with the hook:



    UnhookWindowsHookEx(hookHandle)

     


    Good luck,

    Joe


  • jamesIEDOTNET

    Hi,

    what i m trying to implement is to raise an event whenever a user press "space bar" while typing in ms word so that my application shd run at tht time .

    i had writen a plug in which is working fine but in such case user has to click a menu option , what i actually need is that it shd run automatically when the user press space bar in ms word.


  • SetWindowsHookEx returning 0