Search code examples
c#cursor

Moving cursor c# (cursor.position/cursor.clip not working)


I am currently trying to set my cursor in a certain region of the screen.

I am using the following method:

this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50); 
Cursor.Clip = new Rectangle(this.Location, this.Size);

However nothing actually happens when this code is executed. Can anyone tell me what's going on?


Solution

  • You shouldn't write this line

    this.Cursor = new Cursor(Cursor.Current.Handle); //Remove it

    Here you set the region where mouse cursor will be. This is should be the first line if you want to "lock" mouse cursor in the rectagle. If you don't want to do it then comment this line.

    Cursor.Clip = new Rectangle(this.Location, this.Size);

    Then you can put cursor in the position

    Cursor.Position = new Point(500, 500);

    Small example to show how it can work.

    // After first run uncomment this line and you will see mouse "locking" in your form ===> Cursor.Clip = new Rectangle(this.Location, this.Size);
        for (int i = 0; i < 600; i++)
        {
            //Here you move your cursor.
            //We get current position and shift it by 1.
            Cursor.Position = new Point(Cursor.Position.X - 1, Cursor.Position.Y - 1);
            //Sleep for 100ms
            Thread.Sleep(100);
        }