Windows application - handle taskkill

I have a C # application that has Output Typea value set Windows Application, so this is just a process running in the background. I see the process in the task manager, and I'm trying to gracefully finish it from the command line, and also be able to handle this completion in my code. I ran taskkill /im myprocess.exeand message

SUCCESS: Sent the process termination signal "MyProcess.exe" with PID 61

My problem is that I still see the process in the task manager after that. It closes it if I do taskkill /f, but I certainly do not want this, because I need to run the code before the exit of my process.

How can I process this “completion signal” in my application so that I can complete the necessary material before exiting and then exiting?

+4
source share
1 answer

If you look what youtaskkill really find , it will send a message WM_CLOSEto the process message loop. Therefore, you need to find a way to process this message and exit the application.

The following small test application shows a way to do just that. If you start it from Visual Studio using the CTRL+ F5shortcut (so that the process runs outside the debugger), you can close it with 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();
        }
    }
}
+1
source

Source: https://habr.com/ru/post/1648501/


All Articles