简体   繁体   English

C# 在方法中调用方法时是否可以将 EventArgs 转换为 FormClosingEventArgs?

[英]C# Is it possible to convert EventArgs to FormClosingEventArgs when calling method in a method?

I've made a form closing event when X is pressed, but I also want the 'Exit' button to call this same method yet it draws me error every time I change stuff.当按下 X 时,我创建了一个表单关闭事件,但我也希望“退出”按钮调用相同的方法,但每次更改内容时都会出现错误。

--- This code below is the form closing event --- --- 下面这段代码是表单关闭事件 ---

// if user pressed 'Exit' button or red cross
private void TempConverterForm1_FormClosing(object sender, FormClosingEventArgs e) {
    DialogResult exitdialog = MessageBox.Show("Are you sure you want to quit?", "Quit?", MessageBoxButtons.YesNoCancel);

    if (exitdialog == DialogResult.Yes) {
        e.Cancel = false;
    }

    else {
        e.Cancel = true;
    }
}

--- This code below is the code I'm trying to solve --- ---下面的代码是我要解决的代码---

// if the 'exit' button is pressed
private void btn_Exit_Click(object sender, EventArgs e) {
    TempConverterForm1_FormClosing(sender, (FormClosingEventArgs) e);
}

I've tried without FormClosingEventArgs first but on itself it says that EventArgs can't be converted to closing event.我首先尝试不FormClosingEventArgs ,但它本身说EventArgs无法转换为关闭事件。 I put FormClosingEventArgs but now it tries to convert from MouseEventArgs to FormClosingEventArgs even though I relate to button click and not mouse click.我放FormClosingEventArgs ,但现在它尝试从MouseEventArgs转换为FormClosingEventArgs ,即使我与按钮单击而不是鼠标单击有关。 I tried to do research but the problem repeats and builds up with different error messages and I got lost and decided I need help with this.我试图进行研究,但问题重复出现并随着不同的错误消息累积,我迷路了,决定需要帮助。

Just do this.Close() in btn_Exit_Click.只需在 btn_Exit_Click 中执行 this.Close()。 This will fire Form_Closing correctly with the right arguments, and your cancel will still work.这将使用正确的 arguments 正确触发 Form_Closing,并且您的取消仍然有效。

private void btn_Exit_Click(object sender, EventArgs e)
{
       this.Close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM