【问题标题】:Move cursor by itself in his current position将光标自行移动到当前位置
【发布时间】:2019-12-02 03:15:23
【问题描述】:

我正在开发一个程序,该程序将光标本身移动到他的当前位置。

我已经删除了我之前的问题,因为它不是Minimal and Reproducible question

所以我的程序是这样工作的,我使用GetCursorPos函数获取当前光标位置,然后使用SetCursorPos移动光标。

我的光标按照我的意愿自行移动,但光标位置始终位于屏幕的左上角。

  • 我一般不使用using namespace std;, 不过在这个小程序里用起来没问题

这是我目前的代码,有什么建议吗?

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

using namespace std;

int main()
{
    POINT p;
    BOOL bPos = GetCursorPos(&p);

    while (true) {

        int x = rand() % 10;
        int y = rand() % 10;
        bPos = SetCursorPos(x, y);
    }

    return 0;
}

谢谢!

【问题讨论】:

  • 您永远不会通过调用 srand 来播种随机生成器。您每次都会得到相同的“随机”数字。顺便提一句;请查看<random>
  • @JesperJuhl 谢谢,我修好了,对我的主要问题有什么建议吗?

标签: c++ windows


【解决方案1】:

首先,有几个问题:

  • 在这里包含&lt;iostream&gt;&lt;vector&gt;是没用的。
  • 您保存了SetCursorPos 函数的返回值,但从不使用它。
  • 您永远不会为 rand 函数播种,因此它总是给出相同的结果。

然后,问题是您将xy 随机化在0 - 9 的范围内。
现在,由于坐标(0; 0) 位于左上角,我们可以看到您获得结果的原因。

您可以通过每次在 while 循环中更新当前位置并更改各自当前位置的坐标来获得所需的行为。

#include <windows.h>
#include <ctime>

using namespace std;

int main(){
    srand(time(nullptr));
    POINT current_position;

    while(true){
        GetCursorPos(&current_position);

        int offset = rand() % 2;
        int x_direction = rand() % 2 == 1 ? 1 : -1;
        int y_direction = rand() % 2 == 1 ? 1 : -1;

        SetCursorPos(current_position.x + (offset * x_direction), current_position.y + (offset * y_direction));
        Sleep(10);
    }

    return 0;
}

您可能想做的另一件事是查看&lt;random&gt; 库。它会将您的代码简化为:

#include <thread> // sleep_for()
#include <random>
#include <windows.h>

using namespace std;

int main(){
    mt19937 engine(random_device{}());
    uniform_int_distribution<> range(-1, 1);

    POINT current_position;

    while(true){
        GetCursorPos(&current_position);
        SetCursorPos(current_position.x + range(engine), current_position.y + range(engine));

        this_thread::sleep_for(10ms);
    }

    return 0;
}

注意:更喜欢使用标准的做事方式,在这种情况下,睡觉。

【讨论】:

  • 我已经将这个变量用于光标位置,当我使用你的变量值时,我的光标只是在屏幕上晃来晃去。
  • 我希望能够移动我的鼠标并移动鼠标 10 个像素,而不是 1920 和 1080,如果我使用 1920 和 1080,我的鼠标会从当前位置移动 1920 个像素。
  • 谢谢!但这仍然不是我想做的,让我举个肮脏的例子,让我们以“VineMemz”恶意软件为例,你可以看到鼠标正在像我想做的那样移动自己 *我只举了这个恶意软件的例子,如果你想在 youtube 中搜索 vinememz。
  • 请看一下。
猜你喜欢
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
相关资源
最近更新 更多