2

I have C# wpf application and when I'm exiting i have messagebox "Are you sure you want to exit" and if pressed ok then everything is closing and application is exiting. But when I'm closing the application thru task manager the message box is displayed and after 3-4 seconds the application is exiting. I need to save in database every time the wpf application is closed, even thru task manager. How do I accomplish this? thanks

Sonja
  • 575
  • 1
  • 6
  • 20
  • Side question: if user kills the application via Task Manager (or shutting down Windows) then...are you sure she wants to save changes? Even more than that, are you sure she will always wait to see the message box from your application when simply closing Windows and move away? To persist changes when app closes is, maybe, not the best solution for an application (what about crashes?) – Adriano Repetti Jun 14 '17 at 07:17
  • As noted below (and in the referenced duplicate question), you cannot do this. There are ways to detect a normal closing of the process (and you seem to already be doing that), but there will always be the possibility of your process being terminated without it getting to run any more code. – Peter Duniho Jun 14 '17 at 07:17
  • This is not a duplicate question, this is wpf application not mfc. There are different events. Peter Duniho kindly do necessary so that my question can be answered instead of marking it as duplicate – Sonja Jun 14 '17 at 07:38
  • Adriano, especially when shutting down windows or killing it from task manager I need the information to be saved – Sonja Jun 14 '17 at 12:00

2 Answers2

1

You've got two events that may be of interest Closing and Closed.

Closing

Occurs directly after Close is called, and can be handled to cancel window closure.

and Closed

Occurs when the window is about to close.

You'd use them like this

<Window ... Closing="Window_Closing" Closed="Window_Closed">
    ...
</Window>

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    ...
}

private void Window_Closed(object sender, EventArgs e)
{
    ....
}

As this post says you can still trap the Closing event and handle it from there.

Gareth
  • 913
  • 6
  • 14
-1

What you need to do is a bit complicated, because the user always has the possibility of closing down your app. Other situations when you can't control a good closing of your app is when the PC is shutting down unexpectedly.

Here you are a good link where this topic is also discussed: Prevent C# app from process kill