Get cursor position with respect to the control - C#

Farid-ur-Rahman picture Farid-ur-Rahman · Nov 20, 2011 · Viewed 74.9k times · Source

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.

Answer

BrendanMcK picture BrendanMcK · Nov 20, 2011

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.