简体   繁体   中英

Program doesn't run functions repeatedly (C++)

I am making an autoclicker. The "ClickLoop" function I found on another SO post works, but I am trying to add a key to toggle the autoclicker on and off.

This is my code so far:

#include <windows.h>
#include <iostream>
#include <chrono>
#include <thread>
#include <random>

bool on = false;

void tick () {
    if(GetKeyState('x') & 0x8000) {
        on = !on;
    }
    tick();
};

void WINAPI ClickLoop(int delay) {
    std::cout << "test" << std::endl;
    while ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) == 0) {
        Sleep(1);
    }

    int nCurrKeyState = GetKeyState(VK_LBUTTON);
    int nPrevKeyState;

    do {
        if (on) {
            INPUT Input;
            ZeroMemory(&Input, sizeof(INPUT));
            Input.type = INPUT_MOUSE;

            Input.mi.dwFlags =  MOUSEEVENTF_LEFTUP;
            SendInput(1, &Input, sizeof(INPUT));

            Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
            SendInput(1, &Input, sizeof(INPUT));

            // Delay in MS
            Sleep(delay);

            nPrevKeyState = nCurrKeyState;
            nCurrKeyState = GetKeyState(VK_LBUTTON);

            if ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) == 0)
                break;
        } else {
            break;
        }
    } while (nCurrKeyState != nPrevKeyState);

    ClickLoop(delay);
}

int main() {
    int delay;
    std::cout << "Delay in milliseconds: ";
    std::cin >> delay;
    tick();
    ClickLoop(delay);

    return 0;
}

I then use G++ to compile the code:

g++ main.cpp -o main

After running the "main" executable, I find that it starts up, asks me for the delay and then stops after a couple of seconds.

Why does this happen?

void tick () {
    ...
    tick();
}

This is an endless recursion loop. Once main() calls tick() , the program is stuck in this loop and never reaches ClickLoop() .

void WINAPI ClickLoop(int delay) {
    ...
    ClickLoop(delay);
}

This is also an endless recursion loop.

You need to get rid of these recursive loops.

Another problem I see is that you are using GetKeyState() in places, but GetKeyState() depends on the calling thread having a message loop to process WM_(L|M|R)BUTTON(DOWN|UP) window messages to update the thread's internal keyboard state. But there is no window or message loop in this code.

GetAsyncKeyState() does not depend on a window or a message loop.

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