This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Moving the Mouse Pointer Programmatically

Although rare, there are some situations where you may wish to reposition the mouse pointer programmatically to improve the user experience or to enhance accessibility. This can be easily achieved using standard .NET classes and properties.

Cursor.Position Property

The .NET framework includes a class named "Cursor" that is found within the System.Windows.Forms namespace. This class includes methods that control the behaviour of the mouse pointer and properties that allow you to retrieve and change information relating to the cursor.

The Cursor class's Position property can be used to read the current position of the mouse pointer using screen co-ordinates. This property can also be written to to change the position of the mouse pointer. The new value for the position is provided in a Point structure. As screen co-ordinates are used, the X and Y values in the point represent the distance from the top-left corner of the screen.

For example, to move the mouse pointer to the top-left corner, you can use the following code:

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

Moving the Pointer to the Centre of a Button

One of the most common reasons for moving the mouse pointer is to place it in the centre of a button or other control. This can be demonstrated by creating a form containing a button named "MyButton" and executing the following code:

Point buttonCentre = new Point(MyButton.Width / 2, MyButton.Height / 2);
Point p = MyButton.PointToScreen(buttonCentre);
Cursor.Position = p;

The sample above moves the mouse pointer to the centre of the button by performing three actions. The first line of code creates a Point structure containing the position of the centre of the button. This location is measured relative to the top-left corner of the button itself. The second line of code uses the PointToScreen method to convert the co-ordinates for the centre of the button to screen co-ordinates that can be used with the Cursor.Position property. The third line uses these co-ordinates to move the pointer to the desired location.

28 June 2009