There are at least two issues here.
The Application.ApplicationExit
event is raised only when you've called Application.Run()
and the Run()
method is about to return (e.g. you've called Application.Exit()
or Application.ExitThread()
, or closed the last/main window, etc.). In a non-GUI program where you've never called Application.Run()
, the Application
object doesn't have a chance to raise the event.
Forcefully terminating a process can prevent any more code from executing, including event handlers. For a non-GUI process, a more appropriate event to handle would be AppDomain.ProcessExit
. But even this event might not be raised, if you terminate your process forcefully.
So, try the AppDomain.ProcessExit
event. But be aware that depending on how the process is terminated, even that might not be raised.
If you need more specific help than that, provide a good Minimal, Complete, and Verifiable code example that shows what you've tried, reproduces whatever problem you're having, and explain in precise and specific details what exact behavior the code has now and what you want instead.
Additional reading:
How to run code before program exit?
C# Windows Program Exit Request (Detect Application.Exit) No Forms
How to detect when application terminates?
None of these related posts really seem to cover adequately the "forceful termination" scenario and so aren't technically exact duplicates of your question, but they do provide a variety of good discussion on techniques to detect your own process exiting.