Click here to Skip to main content
15,889,266 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a way to constantly track keys pressed, even when the C++ program is not the active form? I mean that the program is running but is in the background. So can a person be using Word and there still be a way to extract the keys they pressed from the buffer? Thanks a bunch.
Posted

you need to set global keyboard hook using http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx[^]
 
Share this answer
 
Comments
vitalik22123 3-Aug-10 2:28am    
thanks
hi, i don't understand what to put in "HOOKPROC lpfn", "HISTANCE" and "DWORD". Hope someone help me. Thanks.
int main() 
{
	SetWindowsHookEx(WH_KEYBOARD,HOOKPROC,HISTANCE,DWORD);
 
Share this answer
 
First of all, if you install an hook of type WH_KEYBOARD then you are not enabled to track the keys sent to other application; you should use WH_KEYBOARD_LL instead.

See the code snippet below:

C++
HHOOK hHook = NULL;

LRESULT CALLBACK MyLowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
   if (nCode == HC_ACTION)
   {
      // wParam and lParam hold valid data about pressed keys
      KBDLLHOOKSTRUCT* pKb = reinterpret_cast<kbdllhookstruct>(lParam);
      bool bAltKeyHeldDown = (pKb->flags & LLKHF_ALTDOWN) != 0;

      if (bAltKeyHeldDown && pKb->vkCode == VK_F2)
      {
         // Do something when ALT+F2 is pressed
      }
   }

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

// Somewhere in your initialization code...
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyboardProc, GetModuleHandle(NULL), 0);
</kbdllhookstruct>
 
Share this answer
 
Comments
vitalik22123 3-Aug-10 10:23am    
thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900