I have a C# application which's Output Type
is set to Windows Application
, so it is basically just a process running in the background. I can see the process in task manager, and I am trying to gracefully terminate it from the command line, and also be able to handle this termination in my code. I ran taskkill /im myprocess.exe
and the message is
SUCCESS: Sent termination signal to the process "MyProcess.exe" with PID 61
My problem is that I can still see the process in task manager after this. It closes it if I do taskkill /f
but I surely don't want that as I need to run code before my process exits.
How can I handle this "termination signal" in my application so that I can do the necessary pre-exit stuff and then exit?
If you look up what taskkill
actually does you will find that it sends a WM_CLOSE
message to the message loop of the process. So you need to find a way to handle this message and exit the application.
The following small test application shows a way to do just that. If you run it from Visual Studio using the CTRL+F5 shortcut (so that the process runs outside of the debugger) you can actually close it using taskkill /IM [processname]
.
using System;
using System.Security.Permissions;
using System.Windows.Forms;
namespace TaskKillTestApp
{
static class Program
{
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
private class TestMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == /*WM_CLOSE*/ 0x10)
{
Application.Exit();
return true;
}
return false;
}
}
[STAThread]
static void Main()
{
Application.AddMessageFilter(new TestMessageFilter());
Application.Run();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With