简体   繁体   English

杀死 Windows 进程并返回退出代码 0

[英]Kill Windows Process and Return Exit Code 0

Is there a way to kill a process with a C# script and have the process's exit code equal 0?有没有办法使用 C# 脚本终止进程并使进程的退出代码等于 0? I tried using Process.Kill() but that returns exit code -1.我尝试使用 Process.Kill() 但返回退出代码-1。 I am accessing getting the Excel process with the Process.GetProcessesByName() function.我正在使用 Process.GetProcessesByName() function 获取 Excel 进程。 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.看起来有一个 Win32 API function TerminateProcess 将退出代码作为参数,但我在进程 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().编辑:有趣的发现 - 当我在 Windows 任务管理器中找到 Excel 进程时,然后单击“结束任务” Excel 进程以代码 0 退出系统信号。因此,看起来系统信号与任务管理器发送到进程不同。诊断.Kill()。 Now I just need to figure out what signal the Task Manager is sending and send it.现在我只需要弄清楚任务管理器正在发送什么信号并发送它。

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.如果有人知道没有 DllImport 的方法,那么分享它可能会很有用。 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);
        }
    }
}


 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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