2012-01-15 13 views
8

Come sarebbe possibile generare un nuovo modulo, ad es. Form2 da Form1, ma assicurarsi che Form2 è adiacente al Form1, ad esempio:Mostra un altro modulo adiacente a quello generato da C#

enter image description here

+3

I moduli hanno una proprietà ['Location'] (http://msdn.microsoft.com/en-us/library/ms159414.aspx). Questo aiuta? –

+0

@Cody Gray Sì, grazie – Mike

risposta

4

Provare a gestire l'evento LocationChanged del modulo principale.

demo Semplice:

public partial class Form1 : Form { 
    Form2 f2; 

    public Form1() { 
    InitializeComponent(); 
    this.LocationChanged += new EventHandler(Form1_LocationChanged); 
    } 

    private void button1_Click(object sender, EventArgs e) { 
    f2 = new Form2(); 
    f2.StartPosition = FormStartPosition.Manual; 
    f2.Location = new Point(this.Right, this.Top); 
    f2.Height = this.Height; 
    f2.Show(); 
    } 

    void Form1_LocationChanged(object sender, EventArgs e) { 
    if (f2 != null) 
     f2.Location = new Point(this.Right, this.Top); 
    } 
} 
6

Qualcosa di simile:

// button click handler method 

Form2 child = new Form2(); 
child.Location = new Point(this.Location.X + this.Width, 
          this.location.Y); 
child.Show(); 

Prendere la coordinata X della posizione dell'oggetto forma attuale e aggiungere la larghezza della forma, ottenendo così la coordinata X della nuova forma. La coordinata Y rimane la stessa.

+0

Grazie, ma presumo che la finestra non "rimanga incollata" sull'altra finestra/modulo? – Mike

+0

No, non sarà incollato –

+1

@Mike: non hai specificato questo requisito. – Tudor

3
public partial class Form1 : Form 
{ 
    Form2 frm2; 
    public Form1() 
    { 
     InitializeComponent(); 
     frm2 = new Form2(this); 
     frm2.Show(); 
    } 
} 

E:

public partial class Form2 : Form 
{ 
    Form1 frm1; 
    public Form2(Form1 frm1) 
    { 
     InitializeComponent(); 
     this.frm1 = frm1; 
     frm1.Move += new EventHandler(Form1_Move); 
    } 

    void Form1_Move(object sender, EventArgs e) 
    { 
     this.Location = new Point(frm1.Location.X + frm1.Width, frm1.Location.Y); 
    } 
} 

EDIT: (A causa di un commento)

Per rendere Form1 seguire Form2 pure, aggiunge:

Move += new EventHandler(Form2_Move); 

Per Form2 's costruttore .

E:

void Form2_Move(object sender, EventArgs e) 
{ 
    frm1.Location = new Point(Location.X - frm1.Width, Location.Y); 
} 

nella sua classe.

+0

Cosa succede se si sposta il Form2 ' – Groo

+0

@Groo Grazie. Modificato di conseguenza. – ispiro

3

Forse questo ti aiuterà. Button1 è su form1

private void button1_Click(object sender, EventArgs e) 
     { 
      Form2 form2 = new Form2(); 
      form2.StartPosition = FormStartPosition.Manual; 
      form2.SetDesktopLocation(this.Location.X + this.Width, this.Location.Y); 
      form2.ShowDialog(); 
     } 
Problemi correlati