我正在开发一个程序,它将光标本身移动到其当前位置。
我删除了上一个问题,因为它不是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;
}
谢谢!
答案 0 :(得分:1)
首先,有几个问题:
<iostream>
和<vector>
是没有用的。SetCursorPos
函数的返回值,但从不使用它。rand
函数,因此它总是提供相同的结果。然后,问题是您在x
范围内将y
和0 - 9
随机分组。
现在,由于坐标(0; 0)
位于左上角,我们可以看到获得结果的原因。
您可以通过每次在while
循环中更新当前位置并更改相应于其当前位置的坐标来获得所需的行为。
#include <windows.h>
#include <ctime>
using namespace std;
int main(){
srand(time(nullptr));
POINT current_position;
while(true){
GetCursorPos(¤t_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;
}
您可能想做的另一件事是查看<random>
库。这样可以将您的代码简化为:
#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(¤t_position);
SetCursorPos(current_position.x + range(engine), current_position.y + range(engine));
this_thread::sleep_for(10ms);
}
return 0;
}
注意:更喜欢使用标准的做事方式,在这种情况下,就是睡觉。