簡體   English   中英

C#-如何與子窗體一起關閉主窗體(而子窗口必須僅在主窗體關閉時關閉)

[英]C# - How Do I Close Main Form Together With Child Forms (while child windows must close ONLY when main form is closing)

我有一個主窗口和幾個子窗口。 子窗口包含一些數據,因此我不希望它們被關閉。 所以我在FormClosing中將它們隱藏起來,將e.Cancel = true;設置e.Cancel = true;

但是當我要關閉主窗口時(退出應用程序)。 我有一些麻煩要退出它。 首先,它不會關閉。 但是要注意,我要關閉一個額外的變量,我實際上需要2次單擊才能關閉它(問題在執行onFormClosing(mainWIndow, ...)之前onFormClosing(mainWIndow, ...)框架嘗試關閉將首先隱藏自身的子項)。

// main and child windows have this as form closing event proc
private void onFormClosing(object sender, FormClosingEventArgs e)
{
    if (sender == this) // main
    {
        exitApp = true;
    }
    else
        if (sender == formChild) // child
        {
            if (!exitApp)
            {
                e.Cancel = true;
                formChild.Hide();
            }
        }
}

如何一鍵關閉它們?

我也想避免Application.Exit(); 因為我需要確保所有線程都正確關閉。 所以最好是干凈的關閉。

您可以使用Application.Exit()強制應用程序。

自己找到解決方案:

// ...
if (sender == this) // main
{
    exitApp = true;
    FormClosing -= onFormClosing;
    Close();
}
// ...

暫無
暫無

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

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