2

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?

Ledi
  • 51
  • 7
  • Is your complaint that you launch the updater and then quit the main app and doing that causes the updater to quit too? – Caius Jard Jan 11 '22 at 20:42
  • yes, exactly that – Ledi Jan 11 '22 at 20:50
  • It is hard to debug that updater. So if it crashes for some reason, soon after starting up, then it looks like it exited at the same time. Without a debugger that told you about it. Make sure it makes [lots of noise](https://stackoverflow.com/a/3133249/17034) when it crashes. – Hans Passant Jan 11 '22 at 21:41

2 Answers2

1

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
        }
    }
}
Sami
  • 2,050
  • 1
  • 13
  • 25
  • 1
    I did it like this but that's basically the same thing, isn't it? `foreach (var process in Process.GetProcessesByName("MyProcess")) { process.Kill(); }` – Ledi Jan 11 '22 at 23:06
0

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()
phoebus
  • 44
  • 2