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

Windows Programming
.NET 1.1+

Mouse Clipping

Specialised applications can require that the mouse pointer is limited to a fixed portion of the screen, known as a clipping rectangle. This region can be determined and controlled by reading and setting a property of a standard .NET class.

Clipping Rectangles

Under normal circumstance the mouse pointer can be moved freely within the rectangle defined by the screen. This area is the clipping rectangle. You can change the boundaries of the rectangle to restrict the pointer movement. This is useful for specialised applications where the user should not click items outside of the rectangle.

Changing the mouse clipping rectangle should be done with care. Although the clipping is removed by switching between applications or by showing the Windows Start menu, adding clipping can be frustrating for novice users. Those who are unaware of keyboard controls may decide to power down their system unnecessarily to remove the clipping.

Getting the Clipping Rectangle

You can retrieve the current clipping rectangle boundaries using the Clip property of the Cursor class. This static property returns a Rectangle structure containing the position and size of the clipping region. The Cursor class is found in the System.Windows.Forms namespace and Rectangle is in System.Drawing, so add the following using directives:

using System.Drawing;
using System.Windows.Forms;

The code below shows the current clipping rectangle in a message box:


Setting the Clipping Rectangle

The Clip property may be used to constrain the mouse pointer within a specified rectangle. If the mouse pointer is not within the rectangle and the application changing the Clip property is active, the pointer will be moved to a valid position. The following sample code restricts the pointer to a 101 pixel square at the top left corner of the screen:

Cursor.Clip = new Rectangle(0, 0, 100, 100);

A common way to limit the pointer is to use the boundaries of a Windows control. First you convert the client rectangle of the control to screen co-ordinates and then apply them to the Clip property. The code below limits the mouse pointer to the boundaries of a panel control named, "MyPanel".

Cursor.Clip = MyPanel.RectangleToScreen(MyPanel.ClientRectangle);

Clearing the Clipping Rectangle

When you no longer require the clipping you should remove it. To do so, set the Clip property value to Rectangle.Empty, as follows:

Cursor.Clip = Rectangle.Empty;
20 December 2010