Hello every one, I've main form when I press btn I open new form with showDialog() function, I need to move two forms together when I press on main form, because they share in design. how can I move them together either I press on main form and move it or I press on form2 and move it? Thx alot for any suggestion.
A:
The main ingredients are the forms' Top
, Left
, Location
, and Width
properties. Say you have a reference to both forms, called form1
and form2
. You could reposition windows like so:
form2.Location = new Point(form1.Left + form1.Width, form1.Top);
The result is both forms, top aligned, with form2 on the right.
Reference:
kbrimington
2010-08-07 07:19:23
thx kbrimington,but wh I mean,I open frm2 with frm2.showDialog() so,is this way work with me to move main and frm2 together when I press on main form to move it?
Dani AM
2010-08-07 07:28:27
@Dani-AM: Add an event handler to each form's `LocationChanged` event. In the event handler, reposition the opposite form as described above. If you do this in both forms, check the opposite form position prior to updating its location, so as to avoid an infinite loop.
kbrimington
2010-08-07 07:40:34
Good point,I'll check this way.
Dani AM
2010-08-07 08:27:54
@Dani-AM: Great. Consider, also, adding handlers to the `SizeChanged` event if your forms are resizable.
kbrimington
2010-08-07 08:52:39
really appreciate your Follow up @kbrimington ;)
Dani AM
2010-08-07 09:05:45
+1
A:
You could create a separate class to manage the form connections and event handling.
class FormConnector
{
private Form mMainForm;
private List<Form> mConnectedForms = new List<Form>();
private Point mMainLocation;
public FormConnector(Form mainForm)
{
this.mMainForm = mainForm;
this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
this.mMainForm.LocationChanged += new EventHandler(MainForm_LocationChanged);
}
public void ConnectForm(Form form)
{
if (!this.mConnectedForms.Contains(form))
{
this.mConnectedForms.Add(form);
}
}
void MainForm_LocationChanged(object sender, EventArgs e)
{
Point relativeChange = new Point(this.mMainForm.Location.X - this.mMainLocation.X, this.mMainForm.Location.Y - this.mMainLocation.Y);
foreach (Form form in this.mConnectedForms)
{
form.Location = new Point(form.Location.X + relativeChange.X, form.Location.Y + relativeChange.Y);
}
this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
}
}
Now all you have to do is to instantiate a FormConnector and call ConnectForm method with the form you want to connect to.
L.E.O
2010-08-07 16:16:31