實現功能:在現有DLL程序中向特定的EXE窗口中發送模擬鍵盤的消息
使用API根據窗口標題遞歸查找特定的窗口句柄,以後模擬調用。
注意:keybd_event函數不能在VS下使用,因此用SendInput代替使用:
1 int SelfFindWindows(HWND hMainWnd, char* lpName, BYTE keyvalue) 2 { 3 HWND hChildWnd = GetWindow(hMainWnd, GW_CHILD); 4 5 while (hChildWnd != NULL) 6 { 7 char lpChildString[32] ={0}; 8 GetWindowText(hChildWnd, lpChildString, sizeof(lpChildString)); 9 10 if (strstr(lpChildString, lpName)) 11 { 12 SetForegroundWindow(hChildWnd); 13 SetFocus(hChildWnd); 14 15 /* 16 keybd_event(keyvalue, 0, 0, 0); 17 keybd_event(keyvalue, 0, KEYEVENTF_KEYUP, 0); 18 */ 19 INPUT input[2]; 20 memset(input, 0, sizeof(input)); 21 //按下 向下方向鍵 22 input[0].ki.wVk = keyvalue; 23 input[0].type = INPUT_KEYBOARD; 24 //鬆開 向下方向鍵 25 input[1].ki.wVk = keyvalue; 26 input[1].type = INPUT_KEYBOARD; 27 input[1].ki.dwFlags = KEYEVENTF_KEYUP; 28 //該函數合成鍵盤事件和鼠標事件,用來模擬鼠標或者鍵盤操做。事件將被插入在鼠標或者鍵盤處理隊列裏面 29 SendInput(2, input, sizeof(INPUT)); 30 return 1; 31 } 32 33 if (GetWindow(hChildWnd, GW_CHILD)) 34 { 35 if (SelfFindWindows(hChildWnd, lpName, keyvalue)) 36 { 37 return 1; 38 } 39 } 40 else 41 hChildWnd = GetWindow(hChildWnd, GW_HWNDNEXT); 42 } 43 44 return 0; 45 } 46 47 int SendKeyEventToEXE() 48 { 49 HWND hDesk = GetDesktopWindow(); 50 HWND hWnd = GetWindow(hDesk, GW_CHILD); 51 52 while (hWnd != NULL) 53 { 54 char lpString[32] ={0}; 55 GetWindowText(hWnd, lpString, sizeof(lpString)); 56 57 if (strstr(lpString, "Foxit Reader")) 58 { 59 SelfFindWindows(hWnd, "Reader", VK_NEXT); 60 61 return 1; 62 } 63 64 hWnd = GetWindow(hWnd, GW_HWNDNEXT); 65 } 66 return 0; 67 }
附錄:函數