简体   繁体   中英

Windows Application - handle taskkill

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM