SetCursorPos problem.

Jun 6, 2012 at 3:12pm
i was trying to create a small program.
the program moves the cursor key whenever the arrow keys (up,down,left,right) are pressed.

sometime the thing goes smooth and sometimes it just slows down too much.
here is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<windows.h>

int main()
{

    int x=0,y=0;
    while(1)
    {
        Sleep(1);
        if(GetAsyncKeyState(39))
        {
            if(x<1280)
            x++;
            SetCursorPos(x,y);
            Sleep(1);
        }
        if(GetAsyncKeyState(37))
        {
            if(x>0)
            x--;
            SetCursorPos(x,y);
            Sleep(1);
        }
        if(GetAsyncKeyState(40))
        {
            if(y<800)
            y++;
            SetCursorPos(x,y);
            Sleep(1);
        }
        if(GetAsyncKeyState(38))
        {
            if(y>0)
            y--;
            SetCursorPos(x,y);
            Sleep(1);
        }
    }
    return 0;
}


any advice to make things better?
using GNU compiler and codeblocks OS is windows 7.
Jun 6, 2012 at 5:00pm
The problem here is with how fast you are iterating through your loop. I rewrote a few things and got it to work a little better:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<windows.h>

int main()
{
    POINT cursor;
   
    while(!GetAsyncKeyState(VK_ESCAPE))
    {
        GetCursorPos(&cursor);
        
        if(GetAsyncKeyState(39))
        {
            if(cursor.x<1280)
            cursor.x++;
            SetCursorPos(cursor.x,cursor.y);
        }
        if(GetAsyncKeyState(37))
        {
            if(cursor.x>0)
            cursor.x--;
            SetCursorPos(cursor.x,cursor.y);
        }
        if(GetAsyncKeyState(40))
        {
            if(cursor.y<800)
            cursor.y++;
            SetCursorPos(cursor.x,cursor.y);
        }
        if(GetAsyncKeyState(38))
        {
            if(cursor.y > 0)
            cursor.y--;
            SetCursorPos(cursor.x,cursor.y);
        }
        
        Sleep(1);
    }
    return 0;
}


The major change is me consolidating all of your separate "Sleep()" calls into one spot. Sleep() isn't what you want to use here but for some reason I'm having trouble remembering the right function.
Last edited on Jun 6, 2012 at 5:00pm
Jun 6, 2012 at 5:33pm
Jun 6, 2012 at 9:29pm
Is there some way to key WaitForSingleObject() off of keyboard input?
Jun 7, 2012 at 12:42am
No, but if that's the route then I'd say: Keyboard hook.
Jun 7, 2012 at 3:07am
Using the SetWindowsHookEx function to install a key board hook.
Jun 9, 2012 at 9:31am
Thanks for help.
Topic archived. No new replies allowed.