C++模拟键盘消息

实现功能:在现有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 }

 附录:

虚拟键码VK值大全(Virtual-Key_Codes):

 

http://wenku.baidu.com/link?url=cH9r3Ycv2dGlYWjds56q4W-UsDCUgdvrJD3RuW9LZ3812jHqxnyXEZhW4aiAHbZLAxGa-UUgvbh_m3pHeGO5slLDjHHlUZJPF4VXX5x4-fm

 

 

你可能感兴趣的:(C++)