Hi,

When I click the X button of the window, the FormClosing is working as a charm, BUT when I kill the application, or restart the computer the application also closes but the FormClosing does not work.

Why? and what should I do to execute a piece of code on this situation ?

Dani AI

Generated

Short answer: a forcible termination (TerminateProcess / a hard "End Process") does not give the CLR or Win32 window a chance to run managed events, so FormClosing won't run. For planned shutdowns (user logoff / OS shutdown) the system sends session-ending messages that can be handled, but handlers must be short and careful. This explains the behavior mentioned and why saw FormClosing on the X-button but not for a kill/restart scenario.

Recommended handlers (use together for best coverage)

  • Microsoft.Win32.SystemEvents.SessionEnding — receives Windows session-ending notifications (logoff/shutdown). Runs on a non-UI thread.
  • AppDomain.CurrentDomain.ProcessExit — runs when the CLR domain is unloading (normal exits and many shutdown cases).
  • Override WndProc to handle WM_QUERYENDSESSION / WM_ENDSESSION for low-level session messages.
  • Keep FormClosing for normal user closes.

Example pattern (WinForms, C#):

public MainForm()
{
    InitializeComponent();
    Microsoft.Win32.SystemEvents.SessionEnding += OnSessionEnding;
    AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}

private void OnSessionEnding(object s, Microsoft.Win32.SessionEndingEventArgs e)
{
    // do only short, synchronous saves (no UI calls)
    SaveState();
}

private void OnProcessExit(object s, EventArgs e)
{
    SaveState();
}

protected override void WndProc(ref Message m)
{
    const int WM_ENDSESSION = 0x16;
    if (m.Msg == WM_ENDSESSION && m.WParam != IntPtr.Zero)
        SaveState();
    base.WndProc(ref m);
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        Microsoft.Win32.SystemEvents.SessionEnding -= OnSessionEnding;
        AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
    }
    base.Dispose(disposing);
}

Practical cautions and troubleshooting

  • Handlers run with very little time during shutdown; avoid long I/O, network calls, or showing UI. Prefer short, atomic local writes (write to temp file then replace).
  • SystemEvents callbacks happen off the UI thread — marshal only when safe, but prefer doing non-UI saves directly.
  • For critical data, rely on frequent autosave/checkpointing during normal operation rather than only on shutdown handlers; forced kills cannot be intercepted.

This complements ’s explanation and gives concrete places to attach shutdown logic for cases where the OS cooperates; a true hard kill cannot be trapped, so design persistence accordingly.

Recommended Answers

All 2 Replies

when you use taskmanager to "kill" the appliction, it doesn't fire any events, It simply stops the execution, This is how you close an application that has frozen. if you waited for it to handle any events, then it would still be frozen.

as for when you restart the computer or shutdown, the event will be called only if there is enough time, they system tells all applications it is shutting down and only gives them a short amount of time to handle business before it kills them. Windows 7 will show a dialog telling you which applications are still busy and ask you if you want to kill them and shutdown, or cancel. But as for XP, it just kills them after X amount of seconds.

Thanks much for the useful information

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.