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?
 
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);
}
0
 
jkrCommented:
What does 'GetLastError()' tell whe the above fails? E.g.

    if ( hhook == NULL )
    {
        printf( "Error creating keyboard hook, reason %d", GetLastError() ) ;
        return -1 ;
    }
0
 
InteractiveMindAuthor Commented:
.., reasion 1428
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
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."
0
 
InteractiveMindAuthor Commented:
What would I need to pass for the hMod parameter in order to make this work?  :-\
0
 
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.
0
 
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)();
0
 
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. :-(
0
 
jkrCommented:
Hm, it seems that 'DllMain()' isn't called when the DLL is loaded - can you check that with e.g. a 'printf()'?
0
 
InteractiveMindAuthor Commented:
Shoved a printf() at the very beginning of the DllMain() function, and I'm not getting any output from it ...
0
 
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);
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
0
 
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 ...

:-\
0
 
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
0
 
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.
0
 
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.
0
 
InteractiveMindAuthor Commented:
0
 
jkrCommented:
I'd say that depends on kind of info you need. Give it a try.
0
 
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)
0
 
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.
0
 
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
0
 
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.