簡體   English   中英

C#Windows窗體應用程序關閉

[英]C# Windows Forms Application Closing

我制作了一個C#Windows窗體應用程序。 我試圖在按下“ X”或“關閉”按鈕以退出應用程序時彈出一個消息框。 到目前為止,這就是我所擁有的,我不知道這是怎么回事。 當我運行“關閉”按鈕時,消息框不會顯示。 任何幫助,將不勝感激。 謝謝。

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.DialogResult == DialogResult.Cancel)
    {
        if (MessageBox.Show("Do you want to save changes to the data?",
                            "MktAuthorizationData", 
                            MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            e.Cancel = true;
            // Do Something 
        }
    }
}

您需要刪除以下情況

if (this.DialogResult == DialogResult.Cancel)

下面的代碼應該工作

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Do you want to save changes to the data?",
                        "MktAuthorizationData", 
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
            e.Cancel = true;
            // Do Something 
    }
}

如果您尚未訂閱該事件,則需要在InitializeComponent();之后進行此操作InitializeComponent();

this.FormClosing += MainWindow_FormClosing;

您可以添加一個Button Close事件來關閉帶有消息框的窗口窗體。

private void btnClose_Click(object sender, EventArgs e)
    {        

   if (MessageBox.Show("Do you want to save changes to the data?",
                    "MktAuthorizationData", 
                    MessageBoxButtons.YesNo) == DialogResult.Yes)
       {
        e.Cancel = true;
        // Do Something 
       }
   } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM