moving and placing child window near parent window C#
Hay all.
I have a form, by pressing a button a child form is created. i want it to be created near the bounds of the par开发者_StackOverflow社区ent,
if the parent form is moved by the user so does the child window.
Thanks.
First, you need to keep a reference to the child form in the parent. Second, you need to cast a delegate to the parent's Move and Resize events (the same delegate method will suffice) Third, you need to use that method to put your child form where you want it.
The following code is an example of what you want:
public partial class Form1 : Form
{
Form2 _form2;
int _offset = 5;
public Form1()
{
InitializeComponent();
this.Move += new EventHandler(MoveSubForm);
this.Resize +=new EventHandler(MoveSubForm);
}
private void Form1_Load(object sender, EventArgs e)
{
_form2 = new Form2();
_form2.Show();
MoveSubForm(this, e);
}
protected void MoveSubForm(object sender, EventArgs e)
{
if (_form2 != null)
{
_form2.Height = this.Height / 2;
_form2.Width = this.Width / 3;
_form2.Left = this.Left + this.Width + _offset;
_form2.Top = this.Top;
}
}
This will keep your child form in harmony with it's parent with a 5 pixel offset where the child is 1/2 height and 1/3 as wide as the parent. With this example I hope you will be able to get what you want out of your project.
Cheers, CEC
Well, any child window which has its owner set to be its parent window, and opens with a "normal" window state, will by default open in a "cascaded" fashion, slightly down and to the right of its parent. Maybe more detail is needed; do you want an already-opened child to keep its position relative to its parent when the parent is moved? For that, just keep a reference to any child windows the parent opens, and in a handler for the form's LocationChanged event, simply track how much the window moved in the X and Y directions, and move each child by the same amount.
精彩评论