如何从 .NET 解决方案启动另一个应用程序并仅退出第一个应用程序

How to start another application from .NET solution and exit only the first one

我正在编写一个软件并尝试将自动更新程序作为一个单独的应用程序实施到其中。我在同一个解决方案下同时拥有软件本身和更新程序。

当服务器有更新可用时,我的程序会提示用户更新,这部分有效。

我无法调用更新应用程序,然后仅退出第一个程序。

这是我没有的:

private void button2_Click(object sender, EventArgs e)
        {
            // Update
            ExecuteAsAdmin("AutoUpdater.exe");
            //System.Windows.Forms.Application.Exit();
            Process.GetCurrentProcess().Kill();
        }

public void ExecuteAsAdmin(string fileName)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = fileName;
            proc.StartInfo.UseShellExecute = true;
            proc.StartInfo.Verb = "runas";
            proc.Start();
        }

这确实成功启动了 AutoUpdater.exe,但随后两者都存在,第一个程序和 AutoUpdater.exe,后者不应退出,因为应该进行更新。

如何从同一个解决方案中只退出一个程序?

将关闭主应用程序的代码添加到更新程序中。您知道进程名称,因此应该相当容易。通过这种方式,您还可以检查更新程序是否在主应用程序关闭之前实际启动 运行。

下面的代码是从这个答案中借用的: 我自己还没有测试过。

Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
    // now check the modules of the process
    foreach (ProcessModule module in process.Modules)
    {
        if (module.FileName.Equals("MyProcess.exe"))
        {
            process.Kill();
        } else 
        {
         enter code here if process not found
        }
    }
}

这适用于我系统中的最小 winforms 应用程序:

        System.Diagnostics.Process p = System.Diagnostics.Process.Start("notepad.exe");
        Application.Exit();

还有这个:

        ExecuteAsAdmin("notepad.exe");
        Application.Exit()