(模拟按键输入)例子:
#include <winuser.h>
//...
INPUT in[6] = {0}; // user32.dll
in[0].type = INPUT_KEYBOARD;
in[1].type = INPUT_KEYBOARD;
in[2].type = INPUT_KEYBOARD;
in[3].type = INPUT_KEYBOARD;
in[4].type = INPUT_KEYBOARD;
in[5].type = INPUT_KEYBOARD;
in[3].ki.dwFlags |= KEYEVENTF_KEYUP;
in[4].ki.dwFlags |= KEYEVENTF_KEYUP;
in[5].ki.dwFlags |= KEYEVENTF_KEYUP;
in[0].ki.wVk = in[3].ki.wVk = VK_CONTROL;
in[1].ki.wVk = in[4].ki.wVk = VK_MENU;
in[2].ki.wVk = in[5].ki.wVk = VK_RIGHT;
hr = SendInput(6, in, sizeof(INPUT));
KEYEVENTF_KEYUP,释放按键很重要。
函数原型 UINT SendInput{
UINT nInput;
LPINPUT pInput;
INT cbSize;
}
函数说明 该函数合成键盘事件和鼠标事件,用来模拟鼠标或者键盘操作。事件将被插入在鼠标处理队列里面。
参数说明 nInput 指定ninput 数组中元素的个数。就是插入事件的个数。pInput 指向一个类型为INPUT的数组变量,该数组中的每个元素代表一个将要插入到线程事件中去的键盘或鼠标事件。cbSize 指定INPUT结构的大小。如果cbSize不是INPUT结构的大小,则函数将失败返回。
适用平台/头文件和链接库 头文件 winuser.h
链接库 user32.dll
返回值 成功插入了多少个操作事件。如果插入出错可以利用GetLastError来查看错误类型
MSDN:
INPUT
typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; }; } INPUT, *PINPUT, FAR* LPINPUT;
Members
-
type
-
Indicates the type of device information this structure carries. It is one of the following values.
Value Description INPUT_HARDWARE The hi union member is valid. INPUT_KEYBOARD The ki union member is valid. INPUT_MOUSE The mi union member is valid.
mi
- MOUSEINPUT structure that contains information about simulated mouse input. ki
- KEYBDINPUT structure that contains information about simulated keyboard input. hi
- HARDWAREINPUT structure that contains information about a simulated input device message.
typedef struct tagKEYBDINPUT { WORD wVk; WORD wScan; DWORD dwFlags; DWORD time; ULONG_PTR dwExtraInfo; } KEYBDINPUT, *PKEYBDINPUT;
Members
-
wVk
- Provides a virtual-key code. The code must be a value in the range 1 to 254. For more information on virtual-key codes, see Virtual-Key Codes. The Winuser.h header file provides macro definitions (VK_*) for each value. If the dwFlags member specifies KEYEVENTF_UNICODE, then wVk must be 0. wScan
- Provides a hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, then wScan specifies a Unicode character that is to be sent to the foreground application. dwFlags
-
Provides various aspects of a keystroke. This member can be a combination of the following values.
Flag Description KEYEVENTF_EXTENDEDKEY Indicates that the scan code was preceded by a prefix byte that has the value 0xE0 (224). KEYEVENTF_KEYUP Indicates that the key is being released. If this flag is not present, then the key is being pressed. KEYEVENTF_SCANCODE Not supported. KEYEVENTF_UNICODE Not supported.
time
- Data in this member is ignored. dwExtraInfo
- Data in this member is ignored.