views:

52

answers:

3

Is there any good way to handle a forced exit in C#?

I have a formless C# application that talks to an LCD over serial. Once the application is running, the only way to kill it is with task manager. The trouble with this is that the program needs to turn the LCD off when it is done, and it doesn't look as if my Application.ApplicationExit event is ever fired in this condition.

Any ideas?

+4  A: 

Once the application is running, the only way to kill it is with task manager.

My big idea would be to change this.

Stick an icon in the notification area that the user can use to shut your app down properly, or set it up so that running the app again will instead shut down an already-running instance if one exists, or any other way that sounds like a good idea.

Requiring a user to use Task Manager to shut down your application screams poor design.

Anon.
The app isn't meant to ever be closed, and it's for my personal use only. The reason I'm using the task manager analogy is because the program is forced to close when Windows shuts down in the same way.
chris12892
Then you could try hooking the shutdown signal (using `SystemEvents.SessionEnding`).
Anon.
Ah, ok, that's what I was looking for! Thanks!
chris12892
A: 

Write a code in your program loop (with a timer perhaps) to read a file or a registry key. For example if a file at C:\YOURPROGRAM\CLOSEME contains text "closeme", close your program gracefully. Write another program that write that C:\YOURPROGRAM\CLOSEME file. So, whenever you want to shutdown your program, don't use taskmanager, instead, open second program.

VOX
A: 

Some options:

  • Write a separate process with a GUI that can start and stop the main process. For example, when you install the Apache web server on Windows the server itself is installed as a service. It can be started and stopped from the system services management panel, but it also comes with a "monitor" process that sits in the notification area, tells you whether Apache is running and lets you start or stop it manually.
  • If it's acceptable for your use-case, make the application a console application. You can register a handler for when the user presses CTRL+C (see Console.CancelKeyPress) that performs your cleanup before your process exits. This still won't let you handle someone killing the process from Task Manager, but it's very easy to do and might be good enough depending on your situation.
Weeble
Neither will work because...1: The process will still be forced to quit when Windows shuts down2. It isn't suitable for a console application.
chris12892