首页 > 解决方案 > C++ 鼠标功能没有响应,试图创建一个点击模拟器

问题描述

#include <Windows.h>
#include <iostream>
#include <conio.h>

//void MouseRetracer(POINT mousePos, int noOfSaves, int delay)
//{
//  
//}

int main(int argc, char* argv[])
{
    std::cout << "Enter delay between 2 clicks... ";
    int delay;
    std::cin >> delay;
    std::cout << "Hover the mouse to the desired location and press 'k'...\n";
    //std::cin.get();
    std::cout << "Press ENTER to start taking inputs!!!" << std::endl;

    bool quit = true;
    int noOfSaves = 0;
    POINT mousePos[100];

    while (quit)
    {
        if (_kbhit())
        {
            char kbKey = _getch();
            if (kbKey == 'k')
            {
                GetCursorPos(&mousePos[noOfSaves]);
                std::cout << noOfSaves + 1 << " positions saved...\n";
                noOfSaves++;
            }
            if (kbKey == 'q')
                quit = false;
        }
    }

    std::cout << "DO NOT move mouse now!" << std::endl;
    //MouseRetracer(mousePos, noOfSaves, delay);
    for (int i = 0; i < noOfSaves; i++)
    {
        //std::cout << mousePos[i].x << '\t';
        Sleep(delay);

        mouse_event(MOUSEEVENTF_LEFTDOWN, mousePos[i].x, mousePos[i].y, NULL, NULL);
        mouse_event(MOUSEEVENTF_LEFTUP, mousePos[i].x, mousePos[i].y, NULL, NULL);

        std::cout << i + 1 << "th save clicked!\n";
    }

    /*std::cout << "Do this again? (y/n)\n";
    char repeat;
    std::cin >> repeat;

    switch (repeat)
    {
    case 'y':
        system("cls");
        break;
    case 'Y':
        system("cls");
        break;
    default:
        return 0;
    }*/

    return 0;
}

上面的代码可以正确地接受输入,即它正确地创建POINT结构并保存数据mousePos[0]mousePos[1](我通过 Visual Studio 2019 调试器检查过),但它无法使用mouse_event(). 没有错误或警告。问题似乎是mouse_event()即使它在POINT mousePos;使用的其他程序中运行良好。使用POINT mousePos[100]似乎很麻烦。

先感谢您。

标签: c++cwinapivisual-c++

解决方案


用于SetCursorPos设置光标位置,然后用于mouse_event发送鼠标按钮单击事件。以下是我的工作代码。你可以试一试。

for (int i = 0; i < noOfSaves; i++)
{
    Sleep(delay);

    SetCursorPos(mousePos[i].x, mousePos[i].y);

    mouse_event(MOUSEEVENTF_LEFTDOWN, mousePos[i].x, mousePos[i].y, NULL, NULL);
    mouse_event(MOUSEEVENTF_LEFTUP, mousePos[i].x, mousePos[i].y, NULL, NULL);

    std::cout << i + 1 << "th save clicked!\n";
}

注意:建议使用SendInput代替,mouse_event因为该功能已被取代。


推荐阅读