Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a Modal form in a position relative to the a control in the parent window (opener)

Tags:

c#

winforms

Well, I have a form that I open using:

ShowDialog(this);

I try to change the position of the form using its Location property, but I don't understand what exactly is this position relative to? I want to open this form below a certain button. So how can this be done?

Thanks.

like image 1000
Karim Avatar asked Aug 22 '10 04:08

Karim


2 Answers

A Form will expect the co-ordinates relative to the screen’s top-left corner. However, the location of a Control within a Form is relative to the top-left corner of the form.

Use the Control’s Location property to find its location, and then call PointToScreen on the Form object to turn it into screen co-ordinates. Then you can position the new form relative to that.

For example:

var locationInForm = myControl.Location;
var locationOnScreen = mainForm.PointToScreen(locationInForm);

using (var model = new ModelForm())
{
    model.Location = new Point(locationOnScreen.X, locationOnScreen.Y + myControl.Height + 3);
    model.ShowDialog();
}

Actually the top-left corner of the client area of the form.

like image 195
Timwi Avatar answered Sep 20 '22 10:09

Timwi


I preferred this:

myModalForm.Location = New Point(myControl.PointToScreen(Point.Empty).X + myControl.Width, myControl.PointToScreen(Point.Empty).Y)
like image 26
Andrea Antonangeli Avatar answered Sep 19 '22 10:09

Andrea Antonangeli