0

Is there a way to kill a process with a C# script and have the process's exit code equal 0? I tried using Process.Kill() but that returns exit code -1. I am accessing getting the Excel process with the Process.GetProcessesByName() function. It looks like there is a Win32 API function TerminateProcess that takes an Exit Code as a parameter but I can't find anything equivalent in the Process class.

Edit: Interesting discovery- when I find the Excel process in the Windows task manager then click "End task" the Excel process exits with code 0. So, it appears that the signal that the Task Manager sends to the process is different then System.Diagnostics.Kill(). Now I just need to figure out what signal the Task Manager is sending and send it.

sth8119
  • 353
  • 1
  • 4
  • 12
  • "Killing" a process _means_ you don't allow it to return an exit code. You're forcefully terminating the program. – gunr2171 Dec 20 '21 at 19:38
  • Could this help https://stackoverflow.com/a/3411988/2878550 (or via WinAPI https://stackoverflow.com/a/9248477/2878550) ? – Dmitry Dec 20 '21 at 19:47
  • I tried to use the CloseMainWindow() function but the Excel Process still hangs after I run it. It has the same effect as just closing the window in the UI. – sth8119 Dec 20 '21 at 20:03
  • 2
    @gunr2171: And still there is an exit code variable in the OS structure representing the terminated process, which other programs can read. You're correct that termination prevents it from being filled by being returned from the victim process, but your implied conclusion that an exit code no longer makes sense, but that's not true. As OP wrote, `TerminateProcess` does accept an integer argument which becomes the victim process exit code. – Ben Voigt Dec 20 '21 at 21:16

1 Answers1

1

I solved my problem even though it's a bit dirty. If someone knows a way to do it without DllImport it might be useful to share. Here's what I did:

class MyClass
{
    [DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
    public static extern bool TerminateProcess(IntPtr proc, uint uExit);
 
    public void MyFunction()
    {
        foreach (var process in Process.GetProcesssesByName("Excel")
        {
            TerminateProcess(my_process.Handle, 0);
        }
    }
}


 
sth8119
  • 353
  • 1
  • 4
  • 12