Getting the Mouse Pointer Position
Many Windows-based programs require the ability to determine the mouse pointer's location. Sometimes the screen position is used, even if the cursor is beyond the boundaries of a window. In other cases the location relative to a form or control is needed.
Getting the Mouse Pointer's Screen Position
The current cursor location relative to the screen can easily be obtained using the Position property of the Cursor class, which can be found in the System.Windows.Forms namespace. The Position member is a static property of the Cursor class that returns a Point structure containing the X and Y co-ordinates of the mouse pointer. The X co-ordinate is relative to the left edge of the screen and the Y co-ordinate is measured from the top of the screen. Both values are expressed in pixels.
To obtain the current cursor position, you can use the following code:
Point position = Cursor.Position;
Getting the Mouse Pointer's Relative Position
Although the screen location of the pointer can be useful, it is more common to want to obtain the position relative to a form's client area. To achieve this, first the screen position is obtained. This can then be translated to a new Point value that is relative to the top-left corner of a form using the PointToClient method of that form. For example, to retrieve the location relative to the current form, you can use the following code. Note that the X and Y co-ordinates can be negative if the pointer is above or to the left of the window.
Point relativeToForm = this.PointToClient(position)
The PointToClient method is available to the form because it is defined within the Control class, from which Form inherits functionality. This means that the method is also available to any Windows Forms control. This allows you to find the cursor position relative to any control. In the final example code below, the position relative to a button is retrieved.
Point relativeToControl = MyButton.PointToClient(position)
13 July 2010