global keyboard hooks in c

buch11 picture buch11 · Feb 5, 2012 · Viewed 8.4k times · Source

i want to write a global keyboard hook to disallow task switching.When i googled i found a whole lot of codes in c#,cpp (and delphi), but i need some basic concepts about hooking (would be the best if examples are in C).So, kindly suggest the resources,links that can help me understand the thing in C's perspective.

PS: I found one good working example(works on winXP and older versions),but when i tried compiling the code it gives me: enter image description here

And i tried searching the "IDC_" constants in all the headers(default ones that come with MinGW gcc installation and the ones provided by developer),but no luck...If any one can compile the code and make it run please help me.I have not uploaded the source itself here as there are a few header file dependencies and in that case i'd have to post all the code here.

winXP is the target environment but would be better if i get it to run Win7 also.

Answer

Lefteris picture Lefteris · Feb 5, 2012

I will go out on a limb here assuming you are on Windows and you want to capture global keystrokes. A way to do this is to use LowLevelHooks. Look at the following example:

Define this callback function somewhere in your code:

//The function that implements the key logging functionality
LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam )
{
   char pressedKey;
   // Declare a pointer to the KBDLLHOOKSTRUCTdsad
   KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
   switch( wParam )
   {
       case WM_KEYUP: // When the key has been pressed and released
       {
          //get the key code
          pressedKey = (char)pKeyBoard->vkCode;
       }
       break;
       default:
           return CallNextHookEx( NULL, nCode, wParam, lParam );
       break;
   }

    //do something with the pressed key here
      ....

   //according to winapi all functions which implement a hook must return by calling next hook
   return CallNextHookEx( NULL, nCode, wParam, lParam);
}

And then somewhere inside your main function you would set the hook like so:

 //Retrieve the applications instance
 HINSTANCE instance = GetModuleHandle(NULL);
 //Set a global Windows Hook to capture keystrokes using the function declared above
 HHOOK test1 = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, instance,0);

More general information about hooks can be found here. You can also capture other global events with the same exact way only following the directions given in SetWindowsHooksEX documentation.