Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a control's location relative to its Form's location?

Tags:

c#

winforms

I'm searching for a property which gives me a Control's location relative to its Form's location, not to the Form's ClientRectangle's "0,0".

Of course I can convert everything to screen coordinates, but I wonder if there's a more direct way to do this.

like image 371
ispiro Avatar asked Apr 19 '12 20:04

ispiro


1 Answers

You need to convert to screen coordinates and then do some math.

Point controlLoc = form.PointToScreen(myControl.Location);

The form's location is already in screen coordinates.

Now:

Point relativeLoc = new Point(controlLoc.X - form.Location.X, controlLoc.Y - form.Location.Y);

That will give you the location relative to the form's upper-left corner, rather than relative to the form's client area.

like image 152
Jim Mischel Avatar answered Oct 24 '22 22:10

Jim Mischel