将听力事件留在另一种形式。
当我尝试关闭Form2时,Form1上没有任何反应。当Form2关闭时,我想在Form1中做一些事情。
这是我的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();
}
答案 0 :(得分:2)
您需要显示正在实施它的FormClosing
事件的对象。由于您正在创建的新对象位于构造函数中,因此我假设frm2不是您正在显示的Form,这意味着您没有处理该事件。
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");
}
答案 1 :(得分:2)
你创建了一个form2的新实例,并听取它的结束事件 - 但是从你发布的代码中你还没有显示它?不确定我错过了什么,但你认为应该起作用的确有效 - 即:
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");
}
}