C++ use keybd_event a random number of times

时间:2017-04-09 23:55:06

标签: c++ windows

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.

1 个答案:

答案 0 :(得分:0)

你的问题对我来说不太清楚。据我所知,你想按“F' F'键和随机选择[左,上,右,下]中的键并模拟1至10次?如果是这种情况,则代码应如下所示:

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);
}