How to properly listen form events with another fo

2019-07-20 06:52发布

Stuck in listening event to another form.

When I try to close my Form2, nothing happens on Form1. I want to do something in Form1 when Form2 closes.

Here is my code for Form1

public partial class Form1: Form
        {
             public Form1()
            {
                InitializeComponent();

                Form2 frm2= new Form2();
                frm2.FormClosing += new FormClosingEventHandler(frm2_FormClosing);
            }

            void frm2_FormClosing(object sender, FormClosingEventArgs e)
            {
                throw new NotImplementedException();
            }

2条回答
何必那么认真
2楼-- · 2019-07-20 07:47

you create a new instance of form2, and listen to its closing event - but from your posted code you don't ever show it? Not sure what I'm missing but what you think should work does work - i.e :

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.FormClosing += frm2_FormClosing;
            frm2.Show();
        }

        void frm2_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("form 2 closed");
        }
    }
查看更多
姐就是有狂的资本
3楼-- · 2019-07-20 07:49

You will need to show the object which you are implementing it's FormClosing event. Since the new object you are creating is in your constructor I assume that frm2 isn't the Form which you are showing, which means you are not handling the event.

public Form1()
{
    InitializeComponent();

    Form2 frm2 = new Form2();
    frm2.FormClosing += frm2_FormClosing;
    frm2.Show();    
}

void frm2_FormClosing(object sender, FormClosingEventArgs e)
{
    MessageBox.Show("Form2 is closing");
}
查看更多
登录 后发表回答