简体   繁体   English

结帐表格C#

[英]Closing Form C#

Recently I had to edit my program code so that the form will close after creating a PDF. 最近,我不得不编辑程序代码,以便在创建PDF后关闭表单。 In FormClosing() there's a MessageBox.Show for closing or not, depending on the DialogResult . FormClosing()有一个MessageBox.Show是否关闭,具体取决于DialogResult The problem is that when I try to Close() , it shows me the MessageBox , I need to close it without showing it. 问题是当我尝试Close() ,它向我显示了MessageBox ,我需要关闭它而不显示它。 Thanks. 谢谢。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        e.Cancel = true;
    }
}

private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
    showPDf();
    // close pdf but skip MessageBox
}

You can stop listening to the event like so 您可以像这样停止收听事件

private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
    this.FormClosing -= Form1_FormClosing
    showPDf();
    Close();
}

You can use the CloseReason property of the FormClosingEventArgs : 您可以使用CloseReason的财产FormClosingEventArgs

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.ClosingReason == CloseReason.UserClosing && MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        e.Cancel = true;
    }
}

Use e.ClosingReason to find out if the formClosing event was fired by the user's attempt to close the form, or by something else. 使用e.ClosingReason来了解是否由于用户试图关闭表单或其他原因而触发了formClosing事件。

for further reading, go to MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs.closereason(v=vs.110).aspx 要进一步阅读,请访问MSDN: http : //msdn.microsoft.com/zh-cn/library/system.windows.forms.formclosingeventargs.closereason( v= vs.110).aspx

You anyways want to close the form after pdf creation. 无论如何,您都想在创建pdf后关闭表单。 So call Form's Dispose method just after pdf creation like below and no need of registering for the OnFormClosing event 因此,如下所示在创建pdf之后立即调用Form的Dispose方法,而无需注册OnFormClosing事件

private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
    showPDf();
    this.Dispose();
}

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

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