Reputation:
I work on a program that moves the cursor itself on his current position.
I have deleted my previous question because it wasn't Minimal and Reproducible question.
So my program work like this, I get the current cursor position using GetCursorPos
function, and then move the cursor by using SetCursorPos
.
My cursor is moving itself like i wanted, but the cursor position is always at the top left on the screen.
using namespace std;
,
But in this short program no problem to use itThis is my current code, any suggestions ?
#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;
}
Thanks!
Upvotes: 0
Views: 163
Reputation: 543
First of all, a couple of problems:
<iostream>
and <vector>
is useless here.SetCursorPos
function, but never use it.rand
function, so it always gives the same results.Then, the problem is that you randomize both the x
and the y
in a range from 0 - 9
.
Now, since the coordinate (0; 0)
is located at the top-left corner we can see the reason you get the results that you get.
You can get your desired behaviour by updating the current position every time in your while
loop and changing the coordinates respective to their the current position.
#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;
}
Another thing you might want to do is look into the <random>
library. It would simplify your code to this:
#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;
}
Note: prefer using the standard way of doing things, in this case, sleeping.
Upvotes: 1