Error creating keyboard hook.

Hi,

This compiles fine, but an "Error creating keyboard hook" keeps occuring ...


#include <windows.h>
#include <stdio.h>

static HHOOK hhook;

LRESULT CALLBACK LowLevelKeyboardProc( int nCode,
                                       WPARAM wParam,
                                       LPARAM lParam )
{
    printf( "Key Pressed.\n" ) ;
    return CallNextHookEx( hhook, nCode, wParam, lParam ) ;
}

int main()
{
    hhook = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0 ) ;
   
    if ( hhook == NULL )
    {
        printf( "Error creating keyboard hook." ) ;
        return -1 ;
    } else
    {
        printf( "Hook created successfully." ) ;
    }
   
    Sleep( 10 *1000 ) ;
   
    return 0 ;
}


Thanks.
LVL 25
InteractiveMindAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
What does 'GetLastError()' tell whe the above fails? E.g.

    if ( hhook == NULL )
    {
        printf( "Error creating keyboard hook, reason %d", GetLastError() ) ;
        return -1 ;
    }
InteractiveMindAuthor Commented:
.., reasion 1428
InteractiveMindAuthor Commented:
Ah, from:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/system_error_codes__1300-1699_.asp

ERROR_HOOK_NEEDS_HMOD - 1428 - "Cannot set nonlocal hook without a module handle."
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

InteractiveMindAuthor Commented:
What would I need to pass for the hMod parameter in order to make this work?  :-\
jkrCommented:
Puth the whole thing in a DLL and use the module handle, e.g.

HHOOK g_hhk = NULL;
HINSTANCE g_hThisDll;


int APIENTRY    DllMain (   HINSTANCE   hInstance,
                            DWORD       dwReason,
                            LPVOID      lpReserved
                        )
{
    if  (   dwReason    ==  DLL_PROCESS_ATTACH)
        {
            g_hThisDll  =   hInstance;

            return  (   DisableThreadLibraryCalls   (   g_hThisDll));
        }

    return( TRUE);
}

extern "C"
LONG __declspec(dllexport) HookInit ()
{

    g_hhk   =   SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, g_hThisDll, 0 );

    return  (   0);
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
InteractiveMindAuthor Commented:
This okay?


#include <windows.h>
#include <stdio.h>

HHOOK g_hhk = NULL;
HINSTANCE g_hThisDll;

LRESULT CALLBACK LowLevelKeyboardProc( int nCode,
                                       WPARAM wParam,
                                       LPARAM lParam )
{
    printf( "Key Pressed.\n" ) ;
    return CallNextHookEx( g_hhk, nCode, wParam, lParam ) ;
}

int APIENTRY DllMain( HINSTANCE hInstance,
                      DWORD dwReason,
                      LPVOID lpReserved )
{
    if  ( dwReason == DLL_PROCESS_ATTACH )
    {
        g_hThisDll = hInstance;
       
        return (DisableThreadLibraryCalls (g_hThisDll ) ) ;
    }
   
    return( TRUE);
}

extern "C"
LONG __declspec(dllexport) HookInit ()
{
    g_hhk = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, g_hThisDll, 0 );
   
    return( 0);
}



I've never loaded a DLL in C/C++ before — how would I do this?

Thank you.
jkrCommented:
Yup, that's OK.

>>I've never loaded a DLL in C/C++ before — how would I do this?

Just add the import library that you get when building your DLL to your application, then the DLL will be loaded. Or, do that explixitly, e.g. like

typedef LONG (*HOOKINIT)();
HOOKINIT pHookInit = NULL;
HINSTANCE hDll = LoadLibrary("llkbhook.dll");
pHookInit = (HOOKINIT) GetProcAddress(hDll,"HookInit");

(*pHookInit)();
InteractiveMindAuthor Commented:
Ah k. Cheers for that. :)


I edited the HookInit() function to detect any errors:

extern "C"
LONG __declspec(dllexport) HookInit ()
{
    g_hhk = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, g_hThisDll, 0 );
   
    if ( g_hhk == NULL )
    {
        printf( "Error, reason %d", GetLastError() ) ;
    } else
    {
        printf( "Successful." ) ;
    }
   
    return( 0);
}


And it's outputting "Error, reason 1428" — the same as earlier. :-(
jkrCommented:
Hm, it seems that 'DllMain()' isn't called when the DLL is loaded - can you check that with e.g. a 'printf()'?
InteractiveMindAuthor Commented:
Shoved a printf() at the very beginning of the DllMain() function, and I'm not getting any output from it ...
jkrCommented:
OK. I remember you're using Dev-C++, and I don't know what you need to do to set an entry point for a module there, so a workaround would be to

g_hhk = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle("llkbhook.dll"), 0);
InteractiveMindAuthor Commented:
Yay, it's "successfully" creating a hook now (is it a global hook?). :) .. so, can I just scrap the DllMain function from my code now? Or is it still necessary?


Just one problem left though:

Whenever I type a key, my app isn't outputting anything ... whereas based on my LowLevelKeyboardProc function, I'm expecting it to output "Key Pressed.".  :-\

Is it alright that I'm sleeping in my app for 10 seconds in order to keep my app open? Or could this be causing some problem?

#include <windows.h>
#include <stdio.h>

int main()
{
    typedef LONG (*HOOKINIT )();
    HOOKINIT pHookInit = NULL;
    HINSTANCE hDll = LoadLibrary( "KL_DLL.dll" ) ;
   
    pHookInit = (HOOKINIT ) GetProcAddress( hDll, "HookInit" ) ;
   
    (*pHookInit )();
   
    Sleep( 10 *1000 ) ;   // sleep for 10 seconds.
    return 0 ;
}

Cheers
InteractiveMindAuthor Commented:
..However, when I run my program, and then type some text into notepad, it is responding very very slowly — as if my hook is creating a reasonably long delay for each key ...

:-\
jkrCommented:
>>whereas based on my LowLevelKeyboardProc function, I'm expecting it to output "Key Pressed.".  :-\

Almost right, but you won't see it, as most apps don't have a console. Make that

OutputDebugString( "Key Pressed.\n" ) ;

and see it in action using e.g. http://www.sysinternals.com/Utilities/DebugView.html
InteractiveMindAuthor Commented:
Hmm, just gave that a go - and that program isn't outputting any messages..  :-\

So, I tried writing to a file everytime LowLevelKeyboardProc() was called [I called fopen() in the HookInit() function], but there's no output in the log file ...


[ Is there anyway to do this without using a DLL? :) ]

Much appreciated.
jkrCommented:
>>Is there anyway to do this without using a DLL? :)

Nope, for a global hook, you need DLLs - see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwui/html/msdn_hooks32.asp ("Win32 Hooks")

BTW, why are you using a WH_KEYBOARD_LL? A WH_KEYBOARD will be enough to detect keypresses.
InteractiveMindAuthor Commented:
jkrCommented:
I'd say that depends on kind of info you need. Give it a try.
jkrCommented:
BTW, if it is only about keypress detection, I would use

LRESULT CALLBACK HookProc   (   int     nCode,  // hook code
                                WPARAM  wParam, // removal flag
                                LPARAM  lParam  // address of structure with message
                            )
{
    PMSG    pmsg    =   ( PMSG) lParam;

    if  (   0   >   nCode   ||  PM_NOREMOVE ==  wParam)
        {
            return  (   CallNextHookEx  (   g_hhk,
                                            nCode,
                                            wParam,
                                            lParam
                                        )
                    );
        }

    if  (       WM_KEYDOWN  ==  pmsg->message
            ||  WM_KEYUP    ==  pmsg->message  
        )
        {
            /* this one is for us, so check key state */
            OutputDebugString( "Key Pressed.\n" ) ;
        }

    return  (   CallNextHookEx  (   g_hhk,
                                    nCode,
                                    wParam,
                                    lParam
                                )
            );
}

extern "C"
LONG __declspec(dllexport) HookInit ( PXCLIPARGS    pArgs)
{

    if  (   g_hhk)  return  (   ERROR_ALREADY_EXISTS);

    g_hhk   =   SetWindowsHookEx    (   WH_GETMESSAGE,
                                        ( HOOKPROC) HookProc,
                                        g_hThisDll,
                                        0
                                    );

    return  (   0);
}

(taken out of a working project)
InteractiveMindAuthor Commented:
> BTW, if it is only about keypress detection ...
Unfortunately it's not... I am creating a sort of macro application, and need to record/log each key that's pressed.

..On the subject of keylogging (and trojans, etc), they generally consist of just a single EXE... and yet manage to log global key presses, etc.. Is this achieved by unpacking a DLL when they're ran? (Don't worry, I shan't ask you how that's done ;-)).

I shall give just WH_KEYBOARD a go either a little later tonight, or some time tomorrow morning [GMT].

Thanks so far.
trigger-happyCommented:
Regarding the question about having only an EXE and not DLLs for keylogging, this should help: http://neworder.box.sk/newsread.php?newsid=10952

--trigger-happy
InteractiveMindAuthor Commented:
Sorry for delay -- have been pretty busy with other projects also (am constantly changing the priority of my projects)  :)


All help is appreciated, so I'm going to split the points.

But I'm going to give the code provided in trigger-happy's link a go .. and create a new thread regarding the odd compilation error that I get.


Thanks.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.