How to get a control location relative to its shape location?

I am looking for a property that gives me a reference location relative to its location of the form, and not in the ClientRectangle's form of "0.0".

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

+6
source share
4 answers

It seems that the answer is that there is no direct way to do this.

(As I stated in the question, I am looking for a way different from using screen coordinates.)

+2
source

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

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

The location of the form is already in the screen coordinates.

Now:

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

This will give you a location relative to the form in the upper left corner, and not relative to the client area of ​​the form.

+9
source

I think this will answer your question. Note that "this" is a form.

 Rectangle screenCoordinates = control.Parent.ClientToScreen(control.ClientRectangle); Rectangle formCoordinates = this.ScreenToClient(screenCoordinates); 
+3
source

The selected answer is technically correct taking into account the specifics of the question: there is no such property in the .NET environment.

But if you want to get such a property, then this is a control extension that will do the trick. Yes, it uses screen coordinates, but given the general nature of the message header, I am sure that some users landing on this page may find this useful.

By the way, I spent a couple of hours trying to do this without screen coordinates, going through all the control parents. I can never combine these two methods. Perhaps this is due to Hans Passant's comment on the OP about how Aero lies in relation to the size of the window.

 using System; using System.Drawing; using System.Windows.Forms; namespace Cambia { public static class ControlExtensions { public static Point FormRelativeLocation(this Control control, Form form = null) { if (form == null) { form = control.FindForm(); if (form == null) { throw new Exception("Form not found."); } } Point cScreen = control.PointToScreen(control.Location); Point fScreen = form.Location; Point cFormRel = new Point(cScreen.X - fScreen.X, cScreen.Y - fScreen.Y); return cFormRel; } } } 
+1
source

Source: https://habr.com/ru/post/913655/


All Articles