Get cursor position with respect to the control - C#

84,371

Solution 1

You can directly use the Location property of the MouseEventArgs argument passed to your event-handler.

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Text = e.Location.X + ":" + e.Location.Y;      
} 

Solution 2

Use Control.PointToClient to convert a point from screen-relative coords to control-relative coords. If you need to go the other way, use PointToScreen.

Solution 3

The following will give you mouse coordinates relative to your control. For example, this results in (0,0) if mouse is over top left corner of the control:

var coordinates = yourControl.PointToClient(Cursor.Position);

Solution 4

One can use following methods for getting the relative from absolute and absolute from relative coordinates:

Point Control.PointToClient(Point point);

Point Control.PointToScreen(Point point);

Solution 5

Cursor.Position return Point on Screen, but Control.PointToClient(Cursor.Position) returns point on control (e.g. control -> panel). In your case, you have e.Locate which return point on control.

Share:
84,371
Farid-ur-Rahman
Author by

Farid-ur-Rahman

Updated on September 09, 2020

Comments

  • Farid-ur-Rahman
    Farid-ur-Rahman over 3 years

    I want to get the mouse position with respect to the control in which mouse pointer is present. That means when I place the cursor to the starting point (Top-Left corner) of control it should give (0,0). I am using the following code:

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            this.Text = Convert.ToString(Cursor.Position.X + ":" + Cursor.Position.Y);         
        } 
    

    But this gives the position with respect to the screen not to the control.

    Code sample will be appreciated.