EventHandler with FormClosingEventArgs - C#
本文关键字:FormClosingEventArgs with EventHandler | 更新日期: 2023-09-27 18:13:59
我在form .cs中有这个关闭表单代码
public void label7_Click(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Are you sure you want to exit?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (MessageBox.Show("Are you sure you want to exit?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else {
Application.Exit();
}
}
在我的Form.designer.cs
中this.label7.Click += new System.EventHandler(this.label7_Click);
但是它一直显示错误
"没有重载'label7_Click'匹配委托的系统。EventHandler"
我该怎么办?
似乎label7_Click方法不存在
this.label7.Click += new System.EventHandler(this.label7_Click);
void label7_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to exit?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
//
}
else {
Application.Exit();
}
}
'label7_Click'匹配委托没有重载
public void label7_Click(object sender, FormClosingEventArgs e)//this method de is incorrect
Event with FormClosingEventArgs
只适用于Form.FormClosing
事件。将代码修改为:
public void label7_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to exit?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close(); //this closes the form
}
}
您正在尝试将FormClosing事件的事件处理程序设置为标签的单击事件。
这两个事件具有不同的签名,因此是不兼容的。
label_click(object sender, EventArgs e)
MyForm_FormClosing(object sender, FormClosingEventArgs e)
如果你的意图是在用户点击标签时关闭应用程序,那么你需要将事件处理程序更改为
label_click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
如果你的意图是在用户试图退出应用程序时请求确认,那么你需要添加一个FormClosing事件处理程序到你的表单,然后写入
MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// NOTE, you don't want to abort closing when Windows shutdown, right?
if(e.CloseReason == CloseReason.UserClosing)
{
if (MessageBox.Show("Are you sure you want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.No)
{
e.Cancel = true;
}
}
}
声明bool clickStr public bool clickStr = true;
private void label7_Click(object sender, EventArgs e)
{
clicKStr = false;
this.Close();
}
private void BeforeFormClosed(object sender, FormClosingEventArgs e)
{
e.Cancel = clickStr;
}
如果你点击lable7,它将发送false给FormClosingEventArgs并设置cancel为false