C# Get a Control's Position on a Form

C# Get a control's position on a form

I usually combine PointToScreen and PointToClient:

Point locationOnForm = control.FindForm().PointToClient(
control.Parent.PointToScreen(control.Location));

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

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

(As I stated in the question I'm looking for a way other than using screen coordinates.)

C# Get the control at a certain position on a form

You can use the Control.GetChildAtPoint method on the form. You may have to do this recursively if you need to go several levels deep. Please see this answer as well.

c# absolute position of control on screen

To get the Height of your Window caption, you can try this:

int captionHeight = yourForm.PointToScreen(Point.Empty).Y - yourForm.Top;    

To get the Width of the form border, you can try this:

int borderWidth = yourForm.PointToScreen(Point.Empty).X - yourForm.Left;

Also you may want to look at the default caption height by SystemInformation.CaptionHeight.

If you want to get the location of the CaptureBox in screen coordinates, you can use the PointToScreen method:

Point loc = CaptureBox.PointToScreen(Point.Empty);

How to get the Screen position of a control inside a group box control?

Probably you are using PointToScreen on the wrong control...

If you have a groupbox with a button then the following code works just fine:

Point p = groupBox1.PointToScreen(button1.Location);

How could I control location of external form relative to a pictureBox on another form?

The position of child controls on a form is given in child coordinates. In other words, in coordinates that are relative to the parent form.

The position of forms is given in screen coordinates because their parent is the entire screen.

This is called out in the documentation for the different overloads of the Location property.

Control.Location: Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container.

Form.Location: Gets or sets the Point that represents the upper-left corner of the Form in screen coordinates.

So you need to convert the position of the PictureBox on form A from child coordinates into screen coordinates, and then you can use those screen coordinates to set the position of form B.

To do this in WinForms, call the Control.PointToScreen method:

Point childCoords  = myPictureBox.Location;
Point screenCoords = myPictureBox.PointToScreen(childCoords);

myOtherForm.Location = screenCoords;


Related Topics



Leave a reply



Submit