global keyboard hooks in c

不羁的心 提交于 2019-11-30 10:33:29

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!