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

Use the Closing event in the Window, you can handle it like this to prevent it from closing:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
}

if it is pressed confirm button in form2 do action, if it is pressed X-button do nothing:

public class Form2
{
  public bool confirm { get; set; }

    public Form2()
        {
            confirm = false;
            InitializeComponent(); 
        }

   private void Confirm_Button_Click(object sender, RoutedEventArgs e)
    {
       //your code
       confirm = true;
       this.Close();

    }

}

first form:

public void Form2_Closing(object sender, CancelEventArgs e)
        {
            if(Form2.confirm == false) return;

            //your code 
        }

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
  }
}