2014-10-04 144 views
2

我想掛鉤記事本與DLL注入。在exe運行並掛上記事本(我可以告訴成功),並按下了一些鍵,似乎令人高興的是,按鍵卡住了循環或隊列(記事本沒有響應)。解除exe文件後,記事本響應並且所有按下的鍵都出現在文本字段中。WH_KEYBOARD的SetWindowsHookEx卡在循環/隊列中

EXE

#include <iostream> 
#include <fstream> 
#include <windows.h> 
#include <stdio.h> 

HHOOK  hHook  = NULL; 
HWND  handle = NULL; 
HMODULE  dll  = NULL; 
HOOKPROC address = NULL; 
DWORD  thread_id = 0; 

using namespace std; 

int main(){ 

    handle=FindWindow(NULL,L"Untitled - Notepad"); 
    if(handle==NULL){ 
     cout<<"Window not found"<<endl; 
     getchar(); 
     return 0; 
    } 

    thread_id=GetWindowThreadProcessId(handle,NULL); 
    if(thread_id==0){ 
     cout<<"ID not found"<<endl; 
     getchar(); 
     return 0; 
    } 

    dll = LoadLibrary(TEXT("X:\\qt\\hook\\debug\\hook.dll")); 
    if(dll==NULL){ 
     cout<<"hook.dll not found"<<endl; 
     getchar(); 
     return 0; 
    } 

    address=(HOOKPROC)GetProcAddress(dll,"[email protected]"); 
    if(address==NULL){ 
     cout<<"Address not found"<<endl; 
     getchar(); 
     return 0; 
    } 

    hHook=SetWindowsHookEx(WH_KEYBOARD,address,dll,thread_id); 
    if(hHook==NULL){ 
     cout<<"hook was not set"<<endl; 
     return 0; 
    } 

    cout<<"Program successfully hooked"<<endl; 
    cout<<"Press enter to unhook the function and stop the program"<<endl; 
    getchar(); 
    UnhookWindowsHookEx(hHook); 

    return 0; 
} 

DLL

#include "hook.h" 
#include <windows.h> 
#include <iostream> 
#include <fstream> 

using namespace std; 

extern "C"{ 
    __declspec(dllexport) LRESULT CALLBACK CallWndProc(int nCode,WPARAM wParam,LPARAM lParam){ 

     if(nCode<0){ 
      return CallNextHookEx(NULL,nCode,wParam,lParam); 
     } 

     ofstream file; 
     file.open("X:\\qt\\klog\\debug\\function.txt"); 
     file<<"Function keyboard_hook called\n"; 
     file.close(); 
     return CallNextHookEx(NULL,nCode,wParam,lParam); 
    } 
} 

BOOL APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved){ 

    switch(Reason) { 
    case DLL_PROCESS_ATTACH: break; 
    case DLL_PROCESS_DETACH: break; 
    case DLL_THREAD_ATTACH: break; 
    case DLL_THREAD_DETACH: break; 
    } 

    return TRUE; 
} 
+0

從[KeyboardProc回調函數](HTTP: //msdn.mi crosoft.com/en-us/library/windows/desktop/ms644984(v=vs.85).aspx)頁面:'這個鉤子可以在安裝它的線程的上下文中調用。該調用是通過向安裝該鉤子的線程發送消息來完成的。因此,安裝該鉤子的線程必須有一個消息循環。' – 2014-10-04 21:10:21

+0

謝謝@ 500不知道我是如何錯過的。 – DevilBinder 2014-10-05 00:17:20

回答

1

添加調用SetWindowsHookEx和UnhookWindowsHookEx之間的消息循環固定它

while(GetMessage(&Msg, NULL, 0, 0) > 0) 
{ 
    TranslateMessage(&Msg); 
    DispatchMessage(&Msg); 
}