How to catch the event of the window close button(red X button on window right top corner) in wpf form?

前端 未结 6 1301
醉酒成梦
醉酒成梦 2021-01-03 18:22

How can I catch the event of the window close button(red X button on window right top corner) in a WPF form? We have got the closing event, window unloaded event also, but w

6条回答
  •  梦谈多话
    2021-01-03 19:13

    SOLUTION:

    Have a flag to identify if Close() method is called from other than X icon button. (eg: IsNonCloseButtonClicked;)

    Have a conditional statement inside Closing () event method which checks if the IsNonCloseButtonClicked is false.

    If false, the app is trying to close itself through other than X icon button. If true, it means X icon button is clicked for closing this app.

    [Sample Code]

    private void buttonCloseTheApp_Click (object sender, RoutedEventArgs e) {
      IsNonCloseButtonClicked = true;
      this.Close (); // this will trigger the Closing () event method
    }
    
    
    private void MainWindow_Closing (object sender, System.ComponentModel.CancelEventArgs e) {
      if (IsNonCloseButtonClicked) {
        e.Cancel = !IsValidated ();
    
        // Non X button clicked - statements
        if (e.Cancel) {
          IsNonCloseButtonClicked = false; // reset the flag
          return;
        }
      } else {
    
        // X button clicked - statements
      }
    }
    

提交回复
热议问题