所以我正在尝试创建一个键盘记录器,所以显然我需要输入最后输入的字符才能执行此操作。到目前为止,我一直在尝试使用SetWindowsHookEx(),但这还没有工作,我做了回调函数,一切都可以帮助我解决这个问题吗?任何帮助表示赞赏
答案 0 :(得分:0)
您使用SetWindowsHookEx处于正确的轨道上。您可以使用WH_GETMESSAGE,WH_MSGFILTER,WH_KEYBOARD或WH_KEYBOARD_LL中的任何一个取决于哪一个适合您的需要。只要有一个WM_KEYDOWN或WM_KEYUP消息发送到钩子窗口,WH_KEYBOARD挂钩就会调用你的回调函数。 WH_KEYBOARD_LL挂钩将在异步键状态更改之前调用您的回调。你可以看看这里: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx和https://msdn.microsoft.com/en-us/library/windows/desktop/ms644985(v=vs.85).aspx
您需要创建系统范围的挂钩,这就是为什么需要将回调函数实现到dll中的原因。在dll中你可以得到以下内容:
#pragma data_seg (".HookSection")
HHOOK hHook = NULL;
#pragma data_seg ()
#pragma comment(linker,"/SECTION:.HookSection,RWS")
HINSTANCE hDLL = NULL;
InstallHook()
{
hHook = SetWindowsHookEx(WH_KEYBOARD, HookProc, hDLL, 0);
}
UninstallHook()
{
UnhookWindowsHookEx( hHook );
}
注意如何将hHook定义为进程之间的共享变量。 hDll是您在DllMain函数中收到的dll hInstance。
WH_KEYBOARD钩子的回调函数可以定义如下:
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode < 0) // do not process message
return CallNextHookEx(hHook, nCode,
wParam, lParam);
// The wParam is the Virtual Key code of the button being pressed or released.
// You can use it for your logging purposes
// In order to determine if the key was pressed or released you need to examine the lParam bits as described here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx
// If you need to check the state of Shift, Alt, Ctrl then you need to use GetAsyncKeyState function
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
下一步是创建一个exe(可能是一个控制台应用程序)。当您需要启动/停止记录时,这将调用InstallHook和UninstallHook函数。
我给了你一个WH_KEYBOARD的例子,但你也可以试试WH_GETMESSAGE或WH_MSGFILTER钩子。在WH_GETMESSAGE的情况下,回调应该像这样定义:
LRESULT CALLBACK GetMsgProc(_In_ int code, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
if (nCode < 0) // do not process message
return CallNextHookEx(hHook, nCode, wParam, lParam);
switch (nCode)
{
case HC_ACTION:
// You can examine the lParam by casting it to PMSG, like this:
PMSG p = (PMSG)lParam;
// If p->message is WM_KEYDOWN
// the virtual keycode will be written in p->wParam
// If you need to check the state of Shift, Alt, Ctrl then you need to use GetAsyncKeyState function
break;
case PM_NOREMOVE:
break;
default:
break;
}
//
return CallNextHookEx(hHook, nCode, wParam, lParam);
}