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

Time:01-12

I'm writing a software and trying to implement an automatic updater into it as a separate application. I have both the software itself and the updater under the same solution.

When an update is available from a server, my program prompts the user to update, this part works.

I fail to call the updater app and then exit only the first program.

This is what I have not:

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

This does successfully start the AutoUpdater.exe but then exists both, the first program and the AutoUpdater.exe, latter should not be exited as that should do the updating.

How to exit only one program from the same solution?

CodePudding user response:

Add the code to shut down the main app in to the updater. You know the process name so it should be fairly easy. This way you can also check that the updater actually starts running before the main app is shut down.

Code below is borrowed from this answer: https://stackoverflow.com/a/49245781/3279876 and I haven't tested it my self.

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
        }
    }
}

CodePudding user response:

This works with a minimal winforms application in my system:

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

but also this:

        ExecuteAsAdmin("notepad.exe");
        Application.Exit()
  •  Tags:  
  • Related