简体   繁体   中英

C++ use keybd_event a random number of times

I want that my program executes the keybd_event a random number of times per Loop

if (KeyDown(0x46))

     {
          srand(time(NULL));

          keybd_event(VK_DOWN,0x28,(rand() % 1) ,rand() % 1);
          Sleep(rand() % 801 + 5);
          keybd_event(VK_DOWN,0x28, KEYEVENTF_KEYUP, 0);
          Sleep(rand() % 101);
          keybd_event(VK_RIGHT, 0x27, (rand() % 1), rand() % 1);
          Sleep(rand() % 801 + 5);
          keybd_event(VK_RIGHT, 0x27, KEYEVENTF_KEYUP, 0);
          Sleep(rand() % 101);
          keybd_event(VK_UP, 0x26, (rand() % 1), rand() % 1);
          Sleep(rand() % 801 + 5);
          keybd_event(VK_UP, 0x26, KEYEVENTF_KEYUP, 0);
          Sleep(rand() % 101);
          keybd_event(VK_LEFT, 0x25, rand() % 1, rand() % 1);
          Sleep(rand() % 801 + 5);
          keybd_event(VK_LEFT, 0x25, KEYEVENTF_KEYUP, 0);
          Sleep(rand() % 101);

for example I want when I press F that it presses the Up,down,left,right arrow keys randomly between 1 - 10 times. I want a rand() % 10 func in front of the keybd_event. How do I do that?

Thanks.

Your question is not quite clear for me. As far as I understood you want to press 'F' key and randomly choose a key among [LEFT, TOP, RIGHT, DOWN] and emulate it 1 to 10 times? If this is the case then the code should look something like this:

srand(time(NULL));

DWORD dwKeys[] = { VK_DOWN, VK_RIGHT, VK_LEFT, VK_TOP };
const DWORD key = rand() % _countof(dwKeys); // Randomly select a key
int times = rand() % 10;
for (int i = 0; i < times; i++)
{
    EmulateKeyPress(key);
}

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