Rasto
Rasto

Reputation: 17844

How to override default window close operation?

In WPF I want to change default close behaviour of some window, so that when user clics red close button the window does not close, it merely hides (and call some method as well). How can I do that?

Upvotes: 26

Views: 39481

Answers (3)

Ali Haider
Ali Haider

Reputation: 66

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  e.Cancel = true; // this will prevent to close
  `this.Hide();` // it'll hide the window
  // here now you can call any method
}

Upvotes: 3

Jobi Joy
Jobi Joy

Reputation: 50048

Try overriding OnClosing in Window.xaml.cs

private override void OnClosing( object sender, CancelEventArgs e )
{
     e.Cancel = true;
     //Do whatever you want here..
}

Upvotes: 52

user308323
user308323

Reputation:

This page should help.

Closing can be handled to detect when a window is being closed (for example, when Close is called). Furthermore, Closing can be used to prevent a window from closing. To prevent a window from closing, you can set the Cancel property of the CancelEventArgs argument to true.

And

If you want to show and hide a window multiple times during the lifetime of an application, and you don't want to reinstantiate the window each time you show it, you can handle the Closing event, cancel it, and call the Hide method. Then, you can call Show on the same instance to reopen it.

Upvotes: 17

Related Questions