Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Error creating keyboard hook.

Posted on 2006-03-29
22
Medium Priority
?
2,185 Views
Last Modified: 2008-02-01
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.
0
Comment
Question by:InteractiveMind
  • 12
  • 9
22 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 1400 total points
ID: 16323265
What does 'GetLastError()' tell whe the above fails? E.g.

    if ( hhook == NULL )
    {
        printf( "Error creating keyboard hook, reason %d", GetLastError() ) ;
        return -1 ;
    }
0
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323298
.., reasion 1428
0
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323321
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323329
What would I need to pass for the hMod parameter in order to make this work?  :-\
0
 
LVL 86

Accepted Solution

by:
jkr earned 1400 total points
ID: 16323404
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323489
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
 
LVL 86

Assisted Solution

by:jkr
jkr earned 1400 total points
ID: 16323539
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323643
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
 
LVL 86

Assisted Solution

by:jkr
jkr earned 1400 total points
ID: 16323674
Hm, it seems that 'DllMain()' isn't called when the DLL is loaded - can you check that with e.g. a 'printf()'?
0
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323711
Shoved a printf() at the very beginning of the DllMain() function, and I'm not getting any output from it ...
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 1400 total points
ID: 16323760
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323842
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16323866
..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
 
LVL 86

Expert Comment

by:jkr
ID: 16323947
>>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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16324143
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
 
LVL 86

Expert Comment

by:jkr
ID: 16324235
>>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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16324284
0
 
LVL 86

Expert Comment

by:jkr
ID: 16324502
I'd say that depends on kind of info you need. Give it a try.
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 1400 total points
ID: 16325287
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16326303
> 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
 
LVL 14

Assisted Solution

by:trigger-happy
trigger-happy earned 600 total points
ID: 16328074
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
 
LVL 25

Author Comment

by:InteractiveMind
ID: 16487547
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

Featured Post

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.

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
Suggested Courses

810 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