Capture .Net Console Kill or Terminate - c#

So I have a hidden console application called Hidden.exe running.
Another application Call Killer.exe will find the process Hidden.exe or its PID, and Kills the process.
How do i programmatically capture a kill command or a terminate from Task Manager? A user can browse through the process list and 'End Task' on Hidden.exe and I want to be able to capture this event and do some cleanup before it exits.
How can i do this? I have searched around, and explored alternatives from
.NET console application exit event
Send WM_CLOSE message to a process with no window
Can I send a ctrl-C (SIGINT) to an application on Windows?
etc....
But they all dont work or only work in some cases, my case is for a hidden console application and needs to somehow capture a Kill on it. None of the above solution seem to have a 'correct' solution.

There is no such answer. A kill will always work and will fire no event. This is due to security concern to prevent virus and/or malware code.
I've since found another way.

Related

Right way to run, kill and keep process running

In my application, which using another application (run in tray) to print receipts I need to do those three things:
Open process when on mainApplication startup
Close process when mainApplication closing or changing any information about printer
Keep process alive, if it get any error
First point is quiet easy, I just simply
Process.Start("_ReceiptPrinter.exe");
And process working ;)
But now, the two other issues:
Closing process. I've tried this code:
Process[] allProcs = Process.GetProcesses();
foreach (Process proc in allProcs)
{
ProcessThreadCollection myThreads = proc.Threads;
if (proc.ProcessName == "_ReceiptPrinter")
{
proc.Close();
}
}
Unfortunately, I can still see icon in tray, and process is still running.
Keep process alive. My main application is in WPF, that one from tray is written on WinForms. Maybe there is any way to handle ANY WinForm application exit event (well, any, but not this one, which just simply close it from another application), and reopen it?
proc.Close() asks it to close but there is no guarantee. Use:
proc.Kill();
The reason you still see a tray icon is that the icons are cached by an external process (windows explorer.)
The reason process.Close() does not close the application is because the application is not processing window messages (as this call simulates a WM_CLOSE request, per classic Windows API.)
The proper way to close the application is process.Close, not process.Kill(), further, as part of app/window close you need to unregister any tray icons you've registered with the system. This way any normal closure of your application will properly clean-up the tray.
Further, you can use a "critical finalizer" which would be guaranteed to run before application exit, except in total catastrophe scenarios.

How to send a control-break (or equivalent signal) to console application process in .NET?

Suppose I start a Process for running a console application like 7z.exe (7-Zip Archiver). I am creating the Process without a window and I'm redirecting the standard output.
I want to know how to stop the Process other than "Process.Kill", because that causes an incomplete/corrupt archive file to be left behind.
If I press CTRL-BREAK when running 7z.exe from a normal command console window, it shuts down gracefully and deletes the incomplete file.
If cmd.exe can start a process and send it a ctrl-break signal, then how can my own application start a process and send it a ctrl-break (or equivalent) signal, so that the process shuts down gracefully?
You can do a thread.sleep to pause it if need be. If you want to stop it completely I'd set up a watch variable then pause your thread, handle any existing data (this is probably was 7zip is doing), and then do a process.kill. I don't think there is (or know of one) an way to automagically handle aborting a process "gracefully". It is up to you, the programmer, to handle an interrupted exit condition gracefully.

Which event fires when we cancel some App by Windows Task Manager?

I need to know which event fires within an WPF application if I cancel it by Windows Task Manager?
The idea is to terminate internal App. job accurately.
Thank you!
When you use the "Processes" tab there is no event, because your process is simply killed.
When you use the "Applications" tab, a normal WM_CLOSE message is sent to the top level of your application. See the last answer here on how to detect this in a WPF application.
The idea is to terminate internal App. job accurately.
You can't do this reliably. If the user is ending the application that way, something has either gone badly wrong or they simply don't care. There's nothing you can do, you're toast. Don't worry about cleaning up after yourself: the operating system will do that for you, no thank you required.
The best thing that you can do is handle the standard close events. Those will get triggered if the user requests to end your app in a polite way, either via the normal means or through Task Manager (Task Manager will try to ask nicely first if the user clicks "End Task" from the "Applications" tab). But since I assume you're already doing that, you've done all that you can.
Handling the event from Task Manager is not possible as the way it works for ungracefull shut downs of applications.
However, you can try to handle the Application class' SessionEnding event which is described in MSDN at below link:
http://msdn.microsoft.com/en-us/library/system.windows.application.sessionending.aspx

Handling a forced exit

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?
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.
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.
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.

How to handle a C# console application terminating?

If I have a console application, is there any way I can handle the following:
Ctrl-C (I know the answer to this. Using Console.TreatControlCAsInput and Console.CancelKeyPress)
Session termination, such as when someone logs off
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.
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.

Categories

Resources