private void Form1_FormClosing(object sender,
    FormClosingEventArgs e){...}
在視窗被關閉的時候會被啟動
e.CloseReason就是這個event發生的原因,常用如下
| CloseReason | 說明 | 
|---|---|
| UserClosing | 使用者按下此form右上角的關閉按鈕 | 
| TaskManagerClosing | 用工作管理員強制關閉 | 
| WindowsShutDown | 關機的時候所觸發 | 
| UserClApplicationExitCallosing | 所從屬的應用程式被關閉時呼叫 | 
此時可以針對不同的需求來做不同的處理
例如讓使用者做再一次的確認
並用e.Cancel抑制關閉事件的發生
private void Form1_FormClosing(object sender,
    FormClosingEventArgs e)
{
    /// if the close button in the title bar is clicked 
    if (e.CloseReason == CloseReason.UserClosing)
    {
        /// ask the user whether close or not 
        if (MessageBox.Show("Leave?", "warning",
                MessageBoxButtons.YesNo) ==
            DialogResult.No)
        {
            /// cancel the process of closing 
            e.Cancel = true;
        }
    }
}
但是到了WPF之後
Window的Closing事件和應用程式的關閉已經切開了
在Window的Closing事件中仍然可以被制止
private void Window_Closing(object sender, 
    System.ComponentModel.CancelEventArgs e)
{
    /// ask the user whether close or not 
    if (MessageBox.Show("Leave?", "warning",
            MessageBoxButton.YesNo) ==
        MessageBoxResult.No)
    {
        /// cancel the process of closing 
        e.Cancel = true;
    }
}
但這時候已經沒有CloseReason可以選用了
因為單一視窗並不影響Application是否關閉
Application預設的關閉條件是最後的視窗被關閉
所以原先所提供的選項已經不再有意義
這時候如果仍然希望知道Application被關閉的原因
Application有提供SessionEnding事件
在Application的XAML裡面加上
<Application
    ...
    SessionEnding="Application_SessionEnding" >
    <Application.Resources>
    </Application.Resources>
</Application>
在程式碼中會看到
private void Application_SessionEnding(object sender,
    SessionEndingCancelEventArgs e){...}
這時候可以從e.ReasonSessionEnding得到簡單的關閉原因
--
參考資料
WPF - Closing Application
表單右上角之關閉功能

沒有留言:
張貼留言