Left Click - looping while detecting click

Viewed 133

Basically, the code below detects "U" is clicked, and if it's clicked then it checks for the left mouse button being clicked. It works up until that point, say you open it, gives it a click per second value, click 'u', and left-click. After you hold the left click it sends left clicks at the desired speed, but it doesn't stop until you click escape. I need it to stop once you let go of the left click button. I've tried a few different things all of which ending up with it either only sending 2 clicks or just not working. TLDR - need it to detect on key, then if the left click button is held down, sends the clicks at the desired cps, and when you let go of left click it stops clicking. I know it worded terribly, English isn't my first language. bool bClick = false;

while (true)
{
  //toggles it on and off
  if (GetAsyncKeyState('U') & 1)
    bClick = !bClick;
  if (bClick)
  {
    while (GetAsyncKeyState(VK_LBUTTON) < 0)
    {
      while (1)
      {

        INPUT input[2] = {};

        input[0].type = INPUT_MOUSE;
        input[0].mi.dx = x;
        input[0].mi.dy = y;
        input[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;

        input[1] = input[0];
        input[1].mi.dwFlags = MOUSEEVENTF_LEFTUP;

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

        std::cout << "Clicked ";
        std::cout << clicks++;
        std::cout << " times \n";
        Sleep(1000 / cps);
        if (GetAsyncKeyState(VK_ESCAPE))
        {
          break;
        }
      }
    }
  }
}
2 Answers

your program will continuously send click messages when running on my computer, and it will not stop by pressing the'U' or Esc key. (I’m not sure if your problem is that the special button cannot be detected or the click is not issued)

Get rid of the inner-most while loop. It is an infinite loop that is broken only by pressing ESC. The middle while loop is all you need, it stops when the left mouse button is released.

while (true)
{
  //toggles it on and off
  if (GetAsyncKeyState('U') & 1)
    bClick = !bClick;
  if (bClick)
  {
    while (GetAsyncKeyState(VK_LBUTTON) < 0)
    {
       INPUT input[2] = {};

       input[0].type = INPUT_MOUSE;
       input[0].mi.dx = x;
       input[0].mi.dy = y;
       input[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;

       input[1] = input[0];
       input[1].mi.dwFlags = MOUSEEVENTF_LEFTUP;

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

       std::cout << "Clicked ";
       std::cout << clicks++;
       std::cout << " times \n";
       Sleep(1000 / cps);
       if (GetAsyncKeyState(VK_ESCAPE))
       {
         break;
       }
    }
  }
}
Related