开发者

Open Form2 from Form1, close Form1 from Form2

开发者 https://www.devze.com 2023-01-02 04:55 出处:网络
Now, I have two forms, called form1 and form2, in the form1 there\'s a button, when I click it, then open the form2

Now, I have two forms, called form1 and form2, in the form1 there's a button, when I click it, then open the form2

Question: in the form2, I want to create a button when I click it, the form2 close and the form开发者_开发问答1 close. How to do?this


Form1:

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

Form2:

public partial class Form2 : Form
{
    Form opener;

    public Form2(Form parentForm)
    {
        InitializeComponent();
        opener = parentForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        opener.Close();
        this.Close();
    }
}


This works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Form2.Show()


Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.


on the form2.buttonclick put

this.close();

form1 should have object of form2.

you need to subscribe Closing event of form2.

and in closing method put

this.close();


if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1

for example you could add a

public class Form2 : Form
{
    Form2(Form1 parentForm):base()
    {
        this.parentForm = parentForm;
    }

    Form1 parentForm;
    .....
}

field and constructor to Form2

if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2


I did this once for my project, to close one application and open another application.

    System.Threading.Thread newThread;
    Form1 frmNewForm = new Form1;

   newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
        newThread.SetApartmentState(System.Threading.ApartmentState.STA);
        newThread.Start();

And add the following Method. Your newThread.Start will call this method.

    public void frmNewFormThread)()
    {

        Application.Run(frmNewForm);

    }


//program to form1 to form2
private void button1_Click(object sender, EventArgs e)
{
    //MessageBox.Show("Welcome Admin");
    Form2 frm = new Form2();
    frm.Show();
    this.Hide();          
}


private void button1_Click(object sender, EventArgs e)
{
      Form2 m = new Form2();
      m.Show();
      this.Visible = false;
}
0

精彩评论

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

关注公众号