C/C++使用keybd_event模拟键盘按键
1 #include <stdio.h> 2 #include <Windows.h> 3 4 /* 5 设置键盘大小写状态 6 big:为TRUE则切换大写状态,否则切换小写状态 7 */ 8 VOID MySetKeyBig(BOOL big = FALSE); 9 10 /* 11 模拟键盘按键,支持大小写 12 str:需要按出的字符串 13 */ 14 VOID MyAnalogKey(char *str); 15 16 int main(void) 17 { 18 // 当程序运行1.5s时再执行模拟按键,以便选择需要操作的窗口 19 Sleep(1500); 20 MyAnalogKey("Love life,Love BiaoGe.0123456789"); 21 system("pause"); 22 return 0; 23 } 24 25 VOID MySetKeyBig(BOOL big) 26 { 27 // 判断键盘CapsLock键是否开启状态,开启状态则为大写,否则为小写 28 if (GetKeyState(VK_CAPITAL)) 29 { 30 // 如果当前键盘状态为大写,要求改小写,则模拟按键CapsLock切换状态 31 if (!big) 32 { 33 keybd_event(VK_CAPITAL, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 34 keybd_event(VK_CAPITAL, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 35 } 36 } 37 else 38 { 39 // 如果当前键盘状态为小写,要求改大写,则模拟按键CapsLock切换状态 40 if (big) 41 { 42 keybd_event(VK_CAPITAL, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 43 keybd_event(VK_CAPITAL, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 44 } 45 } 46 } 47 48 VOID MyAnalogKey(char *str) 49 { 50 int iLen = 0; 51 char *tmp = NULL; 52 INPUT *keys = NULL; 53 BOOL bOldState = FALSE; 54 55 // 保存此操作前的键盘状态 56 bOldState = (BOOL)GetKeyState(VK_CAPITAL); 57 iLen = lstrlen(str); 58 tmp = (char *)malloc(iLen); 59 memmove(tmp, str, iLen); 60 for (int i = 0; i < iLen; i++) 61 { 62 // 某些符号非直属键盘按键,这里只过滤转换两个,以后用到其它字符自行添加过滤 63 if (tmp[i] == ' ') 64 { 65 // 产生一个击键消息步骤:按下->抬起 66 keybd_event(VK_SPACE, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 67 keybd_event(VK_SPACE, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 68 } 69 else if (tmp[i] == ',') 70 { 71 keybd_event(VK_OEM_COMMA, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 72 keybd_event(VK_OEM_COMMA, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 73 } 74 else if (tmp[i] >= 'a' && tmp[i] <= 'z') 75 { // 根据字符大小写切换键盘大小写状态 76 MySetKeyBig(0); 77 // keybd_event只识别大写 78 keybd_event((BYTE)tmp[i]-32, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 79 keybd_event((BYTE)tmp[i]-32, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 80 } 81 else if ((tmp[i] >= 'A' && tmp[i] <= 'Z') || (tmp[i] >= '0' && tmp[i] <= '9')) 82 { 83 MySetKeyBig(1); 84 keybd_event((BYTE)tmp[i], NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 85 keybd_event((BYTE)tmp[i], NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 86 } 87 else 88 { 89 keybd_event((BYTE)tmp[i]+64, NULL, KEYEVENTF_EXTENDEDKEY | 0, NULL); 90 keybd_event((BYTE)tmp[i]+64, NULL, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, NULL); 91 } 92 } 93 // 恢复此操作之前的键盘状态 94 MySetKeyBig(bOldState); 95 free(tmp); 96 }