所以,听起来你没有订阅你的活动:
这是您的代码的外观:
表格1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 obj = new Form2();
obj.Show();
}
}
表格2
partial class Form2
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "Form2";
this.Text = "Form2";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form2_FormClosed);
this.ResumeLayout(false);
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Form2 closed.");
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Form2 closing.");
}
}
也可以将其全部保存在 Form1 中(就订阅而言):
表格1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 obj = new Form2();
obj.Show();
obj.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form2_FormClosing);
obj.FormClosed += new System.Windows.Forms.FormClosedEventHandler(Form2_FormClosed);
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Form2 closed.");
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Form2 closing.");
}
}
我提供的两个版本的代码已经过测试并且工作正常。但是,您只向我们展示了三种方法,我们不知道您还在做什么可能会导致您的问题。学习如何调试是个好主意。例如,在不执行的代码之前设置一个制动点,即使在感知的“适当”条件下也是如此。然后,您可以单步执行代码并查看发生错误的位置。你会惊讶于你会以这种方式捕捉到多少错误。