Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get cursor position with respect to the control - C#

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.

like image 603
Farid-ur-Rahman Avatar asked Nov 20 '11 11:11

Farid-ur-Rahman


People also ask

How do I get the cursor position in Qt?

To set or get the position of the mouse cursor use the static methods QCursor::pos() and QCursor::setPos().


2 Answers

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.

like image 189
BrendanMcK Avatar answered Nov 09 '22 21:11

BrendanMcK


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;       }  
like image 35
Ani Avatar answered Nov 09 '22 21:11

Ani