开发者

Take control of another already opened form in C#

开发者 https://www.devze.com 2023-03-23 14:30 出处:网络
I\'m using Compact Framework 2.0 for an application in Windows CE 5.0. I\'m having trouble changing control between different forms.

I'm using Compact Framework 2.0 for an application in Windows CE 5.0.

I'm having trouble changing control between different forms.

I created a simple example in order to show this.

Imagine that you have two forms, the first form has a button in order to load the second form.

When you click the button and the second form is loaded you may wanna have a control in order to go back to the first form or may be you simply want to close the first form once the second one is loaded.

Here is an example about closing the 开发者_开发百科first form once the second one is loaded:

public partial class Form1 : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
        Form2 secondForm = new Form2();
        secondForm.Show();            
    }
}

But unfortunately this closes both forms, not only the current one (form1).

So I think this must be made inside the second form code, but I don't know how to access the first form from it.

Any suggestions?


The reason both forms are closing is because Form2's parent is Form1. The way WinForms works, is that if the parent is closed (this.Close()) then any children will be closed automatically.

The typical way to do this would actually be to use secondForm.ShowDialog(). This would keep the first form in the background, but make it un-selectable. If you do want to get rid of the current form Hide it instead:

this.Hide();
Form2 secondForm = new Form2();
secondForm.Show();

You'll probably then want a method, hooked up to the secondForm.Closed event to call this.Show() to ensure that your form re-appears.


Form1 is you MainForm which is created and started in the Program.cs. If this Form is closed. The whole Application ends. Try to Hide Form1 like lan showed before or use a Controller-Class to coordinate through the both Form´s.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号