[英]FormClosing and FormClosed events do not work
我正在开发一个C#
应用程序,我需要在用户关闭表单之前进行一些验证。
我尝试使用FormClosing
事件,但是没有用,后来我使用了FormClosed
事件,但还是一样。
问题是,当我单击“关闭按钮”(在表单顶部)时,它什么也没做,但我在表单属性和所有内容中都有事件。
这是我的代码:
private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
{
//things I have to do
//...
//...
if(bandera==true)
Application.Exit();
}
和
private void Inicio_FormClosed_1(object sender, FormClosingEventArgs e)
{
//things I have to do
//...
//...
if(bandera==true)
Application.Exit();
}
任何的想法?
谢谢
这两个事件都应该正常工作。 只需打开一个新项目并进行这个简单的测试:
private void Form1_Load(object sender, EventArgs e)
{
this.FormClosing += new FormClosingEventHandler(Inicio_FormClosing_1);
this.FormClosed += new FormClosedEventHandler(Inicio_FormClosed_1);
}
private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
{
//Things while closing
}
private void Inicio_FormClosed_1(object sender, FormClosedEventArgs e)
{
//Things when closed
}
如果在这些方法中设置断点,您会看到在单击关闭按钮后到达它们。 您的事件附加代码中似乎存在一些问题。 例如: Inicio_FormClosed_1(object sender, FormClosingEventArgs e)
是错误的,只要它应该带一个FormClosedEventArgs
参数; 因此,此方法肯定与FormClosed event
(否则,代码将无法编译)。
我发现了错误;
这里:(当我初始化我的表单时)
public Inicio()
{
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(635, 332);
this.StartPosition = FormStartPosition.CenterScreen;
llenaForm(nombreFormulario);
Application.EnableVisualStyles();
}
我只需要: InitializeComponent();
我误删了
它应该是:
public Inicio()
{
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScroll = true;`
InitializeComponent();//<<<<<<<<-------------------
this.ClientSize = new System.Drawing.Size(635, 332);
this.StartPosition = FormStartPosition.CenterScreen;
llenaForm(nombreFormulario);
Application.EnableVisualStyles();
}
十分感谢大家!
为了防止用户关闭表单以响应某些验证,您需要设置FormClosingEventArgs.Cancel = true
。
例如:
private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
{
if (string.IsNullOrEmpty(txtSomethingRequired.Text))
{
MessageBox.Show("Something is required here!");
if (txtSomethingRequired.CanFocus) txtSomethingRequired.Focus();
e.Cancel = true;
return;
}
}
您只能在FormClosing
事件中进行验证以防止表单关闭; 如果你等到FormClosed
已经太晚了。
我注意到您的方法名称末尾有一个“_1”。 你重命名了这些方法吗?
如果是这样,您的 UI 代码(设计器文件)将需要使用这些新方法名称进行更新。
您可以在这些方法中放置一个断点以查看它们是否被调用。
作为旁注,Form.Hide() 方法不会引发 form_closed 或 form_closed 事件
我也遇到了类似的问题,它是由使用Dispose()
引起的。 确保您使用Close()
来引发关闭/关闭事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.