Handle a WPF Exit Event Handle a WPF Exit Event wpf wpf

Handle a WPF Exit Event


You can hook the event Closing on your main window like this -

<Window Closing="Window_Closing">

And in your event set the e.Cancel to true to stop the window from closing. In your case you can maintain some field which will be set once you get notification from client that he's done with cleanUp and its safe now to close the window. Simply set that value to e.Cancel

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


If you want stop the operating system being shut down, or at least clean up before it does, you need to handle the Application.SessionEnding.

Related: Handling System Shutdown in WPF