简体   繁体   中英

Keyboard simulation fail

I am making a program and i need it to type a random letter from an array. This is how i tried to do it:

{
srand ( time(NULL) );
WORD arrayNum[4] = {0x41, 0x42, 0x43, 0x44};
int RandIndex = rand() % 4;

INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.ki.wVk = arrayNum; 
ip.ki.dwFlags = 0; 
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_KEYUP; 
SendInput(1, &ip, sizeof(INPUT));
}

I must say i am new with this and i don't really know what should i do. The error i get says:

invalid conversion from 'WORD* {aka short unsigned int*}' to 'WORD {aka short unsigned int}' [-fpermissive]

This confuses me a lot..

I think the issue here is in this line:

ip.ki.wVk = arrayNum;

Here, the wVk field is supposed to be a WORD representing the virtual key code to send . However, you've assigned it arrayNum , which is an array of WORD s. Based on your code, I think you meant

ip.ki.wVk = arrayNum[RandIndex];

since you weren't using RandIndex anywhere. Going forward, I'd recommend compiling with the warning level turned all the way up, since it probably would have flagged the non-use of RandIndex in the code.

(Also, if you do ask more questions on Stack Overflow, please try to include more information about the error message. I had to look up the docs to determine which line that particular error occurred on. It's a lot easier for people to help out if they can see the specific line where things went wrong.)

You are passing the actual array itself to wVk when you should be passing a specific element of the array instead:

ip.ki.wVk = arrayNum[RandIndex]; 

That being said, I would suggest using the KEYEVENTF_UNICODE flag when sending text characters with SendInput() , don't use virtual key codes. And you should pass 2 INPUT structures in one call to SendInput() , like @IInspectable suggested. Don't call SendInput() twice for each INPUT , that defeats some of the benefits of using SendInput() :

srand ( time(NULL) );
LPCWSTR chars = L"ABCD";
int RandIndex = rand() % 4;

INPUT ip[2];
memset(ip, 0, sizeof(ip));

ip[0].type = INPUT_KEYBOARD;
ip[0].ki.wScan = (WORD) chars[RandIndex]; 
ip[0].ki.dwFlags = KEYEVENTF_UNICODE;

memcpy(&ip[1], &ip[0], sizeof(INPUT));
ip[1].ki.dwFlags |= KEYEVENTF_KEYUP; 

SendInput(2, ip, sizeof(INPUT));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM