64,682
社区成员
发帖
与我相关
我的任务
分享
LRESULT CALLBACK KeyboardHookProc(int nCode,
WPARAM wParam,
LPARAM lParam
)
{
DebugPrint(_T("KeyboardHookProc(%d,0x%x,0x%x)"), nCode, wParam, lParam);
MessageBeep(0);
if(nCode < 0) {
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
BOOL installed = InstallHook();
if(installed)
{
DebugPrint(_T("Hook installation finished, listening keyboard inputs...\r\n"));
}
else
{
DebugPrint(_T("Hook not installed, exiting...\r\n"));
return GetLastError();
}
WaitForSingleObject(hExitEvent, INFINITE);
DebugPrint(_T("UninstallHook() called, exiting...\r\n"));
return 0;
}
VOID InstallHookDelayed()
{
hExitEvent = CreateEvent(NULL, TRUE, FALSE, _T("Can Exit"));
hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
}
BOOL InstallHook()
{
if(hHook != NULL)
{
DebugPrint(_T("Hook already installed.\r\n"));
return TRUE;
}
DebugPrint(_T("Installing hook...\r\n"));
DebugPrint(_T("Updating key state..."));
UpdateKeyState();
DebugPrint(_T("Done.\r\nInstalling keyboard hook..."));
hHook = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardHookProc, hDllInstance, 0);
if(hHook != NULL)
{
DebugPrint(_T("Done.! Hook ID is 0x%x.\r\n"), hHook);
}
else
{
DebugPrint(_T("Failed ! Error code : %d.\r\n"), GetLastError());
}
return hHook != NULL;
}
BOOL UninstallHook()
{
if(NULL == hHook)
{
return TRUE;
}
SetEvent(hExitEvent);
WaitForSingleObject(hThread, 1000);
CloseHandle(hThread);
CloseHandle(hExitEvent);
hThread = NULL;
DebugPrint(_T("Uninstall hook : 0x%x.\r\n"), hHook);
BOOL bResult = UnhookWindowsHookEx(hHook);
hHook = NULL;
return bResult;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hDllInstance = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DebugPrint(_T("Installing dll 0x%x...\r\n"), hDllInstance);
InstallHookDelayed();
//InstallHook();
break;
case DLL_PROCESS_DETACH:
DebugPrint(_T("Uninstalling dll...\r\n"));
UninstallHook();
break;
}
return TRUE;
}
// Get the function pointer to LoadLibraryW
PTHREAD_START_ROUTINE pfnLoadLibraryW = (PTHREAD_START_ROUTINE)GetProcAddress(
GetModuleHandle(_T("Kernel32")),
"LoadLibraryW");
if(NULL == pfnLoadLibraryW)
__leave;
DWORD hThreadId = 0;
// Create a remoate thread that calls LoadLibrary(pszLibraryPathRemote);
hThread = CreateRemoteThread(
hProcess,
NULL,
0,
pfnLoadLibraryW,
pszLibraryPathRemote,
0,
&hThreadId);
if(NULL == hThread)
__leave;
// Wait untill the library is loaded.
WaitForSingleObject(hThread, INFINITE);