Y.E.P
Y.E.P

Reputation: 1207

getting the 'name of the application' along with the key taps

To record the key taps I install the hook as :

BOOL WINAPI installHook(HINSTANCE hinstDLL, DWORD fwdReason, LPVOID lpvReserved) {
handleKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hinstDLL, 0);
MSG msg;

while(GetMessage(&msg, NULL, 0, 0)){
  TranslateMessage(&msg);
  DispatchMessage(&msg);
}
return msg.wParam;
}

static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
  // write here
}

Is there any way I can know the application name where the keys are currently being tapped ? Like I have opened notepad an writing something , can I get the name of the application which is notepad along with the key taps ? Same goes for some other application like mozilla firefox.

Upvotes: 0

Views: 146

Answers (1)

Ryan
Ryan

Reputation: 2404

The inside of your hook should look like so:

static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    // if it is not a keydown event, continue the chain
    if(HC_ACTION != nCode || WM_KEYDOWN != wParam)
        return CallNextHookEx(0, nCode, wParam, lParam);

    const KBDLLHOOKSTRUCT* messageInfo = reinterpret_cast<const KBDLLHOOKSTRUCT*>(lParam);

    // add more code here...

    // tell Windows we processed the hook
    return 1;
}

messageinfo.vkCode will contain the key codes your looking for. The official list of these codes is at: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx

Keys usually get typed into the foreground window (although sometimes strange window layouts happens). You can get the title of the foreground window like this:

TCHAR title[100]; // increase size for longer titles
GetWindowText(GetForegroundWindow(), title, 100);

If you want to get the name of the program instead, use:

TCHAR title[100]; // increase size for longer program names
GetWindowModuleFileName(GetForegroundWindow(), title, 100);

And, remember to add error checking and check the documentation.

Upvotes: 2

Related Questions