7

If I have a console application, is there any way I can handle the following:

  1. Ctrl-C (I know the answer to this. Using Console.TreatControlCAsInput and Console.CancelKeyPress)
  2. Session termination, such as when someone logs off
  3. Process exit, such as when someone uses the task manager to close the application.

I know that if I was writing a unix application, I would handle various signals to catch the request to close (SIGTERM from memory), but I also know I need to handle these messages pretty quickly and exit before the system does a kill -9 (SIGKILL).

But for a C# console application, I'm not sure how to do this.

Nick Randell
  • 17,805
  • 18
  • 59
  • 74
  • I had to do this the other day, I cant recall what I did. Found the answer pretty easy on Google. Will post the answer when I get home if you have not found a solution yet. Edit: have a look here: http://bytes.com/topic/c-sharp/answers/273227-console-application-close#post1092937 – leppie Mar 31 '10 at 11:59
  • You'll need to P/Invoke SetConsoleCtrlHandler. Easy to google. – Hans Passant Mar 31 '10 at 12:32
  • 1
    You can't catch a SIGKILL. SIGKILL forces the program to close without calling any signal handler, and can't be trapped or ignored. – Marco Sulla Jun 23 '16 at 19:00
  • If you want to handle the process exit, take a look at these questions: [Capture console exit C#](https://stackoverflow.com/questions/474679/capture-console-exit-c-sharp), [How to handle “End Task” from Task Manager in .NET 5 console app?](https://stackoverflow.com/questions/65710454/how-to-handle-end-task-from-task-manager-in-net-5-console-app). – Robin Hartmann Jan 14 '21 at 22:11

1 Answers1

5

Session termination, such as when someone logs off

Handle the SystemEvents.SessionEnded event.

Process exit, such as when someone uses the task manager to close the application.

If you mean, if someone kills the application from the taskbar, I dont think you can handle that.

Ram
  • 1,097
  • 2
  • 12
  • 24
  • You actually **can** handle if the user closes the application from the taskbar or by using the `X` button, as described in the answers to [this question](https://stackoverflow.com/questions/474679/capture-console-exit-c-sharp). – Robin Hartmann Jan 14 '21 at 22:07