void keybd_event(BYTE bVk, BYTE bScan, DWORD dwFlags, ULONG_PTR dwExtraInfo);
bVk:虚拟键码
bScan:键的硬件扫描码,一般置为0
dwFlags:一般为0或KEYEVENTF_KEYUP,置为0表示键按下
dwExtraInfo:与按键关联的附加值,一般为0
这个函数已被取代。建议使用SendInput替代它
示例
#include <Windows.h> int main() { Sleep(2000); keybd_event(VK_CONTROL, 0, 0, 0); //按下Control keybd_event('A', 0, 0, 0); //按下A keybd_event('A', 0, KEYEVENTF_KEYUP, 0); //释放A keybd_event('X', 0, 0, 0); //按下X keybd_event('X', 0, KEYEVENTF_KEYUP, 0); //释放X keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); //释放Control return 0; }
UINT SendInput(UINT cInputs, LPINPUT pInputs, int cbSize);
cInputs:pInputs数组中结构的数量
pInputs:INPUT结构的数组。每个结构代表一个要被插入键盘或鼠标输入流的事件
cbSize:一个INPUT结构的大小,以字节为单位
示例
#include <Windows.h> int main() { Sleep(2000); INPUT inputs[] = { { INPUT_KEYBOARD, {.ki = { VK_CONTROL, 0, 0, 0, 0 } } }, //按下Control { INPUT_KEYBOARD, {.ki = { 'A', 0, 0, 0, 0 } } }, //按下A { INPUT_KEYBOARD, {.ki = { 'A', 0, KEYEVENTF_KEYUP, 0, 0 } } }, //释放A { INPUT_KEYBOARD, {.ki = { 'X', 0, 0, 0, 0 } } }, //按下X { INPUT_KEYBOARD, {.ki = { 'X', 0, KEYEVENTF_KEYUP, 0, 0 } } }, //释放X { INPUT_KEYBOARD, {.ki = { VK_CONTROL, 0, KEYEVENTF_KEYUP, 0, 0 } } } //释放Control }; SendInput(sizeof inputs / sizeof(INPUT), inputs, sizeof(INPUT)); return 0; }
注意:在这个示例中,对数组inputs的初始化,采用的是C语言的风格,C++不支持这样的语法
在C++中,可以这么写
#include <Windows.h> int main() { Sleep(2000); INPUT inputs[6]; inputs[0].type = INPUT_KEYBOARD; inputs[0].ki = { VK_CONTROL, 0, 0, 0, 0 }; //按下Control inputs[1].type = INPUT_KEYBOARD; inputs[1].ki = { 'A', 0, 0, 0, 0 }; //按下A inputs[2].type = INPUT_KEYBOARD; inputs[2].ki = { 'A', 0, KEYEVENTF_KEYUP, 0, 0 }; //释放A inputs[3].type = INPUT_KEYBOARD; inputs[3].ki = { 'X', 0, 0, 0, 0 }; //按下X inputs[4].type = INPUT_KEYBOARD; inputs[4].ki = { 'X', 0, KEYEVENTF_KEYUP, 0, 0 }; //释放X inputs[5].type = INPUT_KEYBOARD; inputs[5].ki = { VK_CONTROL, 0, KEYEVENTF_KEYUP, 0, 0 }; //释放Control SendInput(sizeof inputs / sizeof(INPUT), inputs, sizeof(INPUT)); return 0; }