Restart an application by itself

2019-01-21 20:38发布

I want to build my application with the function to restart itself. I found on codeproject

ProcessStartInfo Info=new ProcessStartInfo();
Info.Arguments="/C choice /C Y /N /D Y /T 3 & Del "+
               Application.ExecutablePath;
Info.WindowStyle=ProcessWindowStyle.Hidden;
Info.CreateNoWindow=true;
Info.FileName="cmd.exe";
Process.Start(Info); 
Application.Exit();

This does not work at all... And the other problem is, how to start it again like this? Maybe there are also arguments to start applications.

Edit:

http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=31454&av=58703

9条回答
We Are One
2楼-- · 2019-01-21 20:50

You have the initial application A, you want to restart. So, When you want to kill A, a little application B is started, B kill A, then B start A, and kill B.

To start a process:

Process.Start("A.exe");

To kill a process, is something like this

Process[] procs = Process.GetProcessesByName("B");

foreach (Process proc in procs)
   proc.Kill();
查看更多
smile是对你的礼貌
3楼-- · 2019-01-21 20:50

Another way of doing this which feels a little cleaner than these solutions is to run a batch file which includes a specific delay to wait for the current application to terminate. This has the added benefit of preventing the two application instances from being open at the same time.

Example windows batch file ("restart.bat"):

sleep 5
start "" "C:\Dev\MyApplication.exe"

In the application, add this code:

// Launch the restart batch file
Process.Start(@"C:\Dev\restart.bat");

// Close the current application (for WPF case)
Application.Current.MainWindow.Close();

// Close the current application (for WinForms case)
Application.Exit();
查看更多
小情绪 Triste *
4楼-- · 2019-01-21 20:51

Why not just the following?

Process.Start(Application.ExecutablePath); 
Application.Exit();

If you want to be sure the app does not run twice either use Environment.Exit(-1) which kills the process instantaneously (not really the nice way) or something like starting a second app, which checks for the process of the main app and starts it again as soon as the process is gone.

查看更多
Deceive 欺骗
5楼-- · 2019-01-21 20:54

Why not use

Application.Restart();

??

More on Restart

查看更多
Animai°情兽
6楼-- · 2019-01-21 20:54

My solution:

        private static bool _exiting;
    private static readonly object SynchObj = new object();

        public static void ApplicationRestart(params string[] commandLine)
    {
        lock (SynchObj)
        {
            if (Assembly.GetEntryAssembly() == null)
            {
                throw new NotSupportedException("RestartNotSupported");
            }

            if (_exiting)
            {
                return;
            }

            _exiting = true;

            if (Environment.OSVersion.Version.Major < 6)
            {
                return;
            }

            bool cancelExit = true;

            try
            {
                List<Form> openForms = Application.OpenForms.OfType<Form>().ToList();

                for (int i = openForms.Count - 1; i >= 0; i--)
                {
                    Form f = openForms[i];

                    if (f.InvokeRequired)
                    {
                        f.Invoke(new MethodInvoker(() =>
                        {
                            f.FormClosing += (sender, args) => cancelExit = args.Cancel;
                            f.Close();
                        }));
                    }
                    else
                    {
                        f.FormClosing += (sender, args) => cancelExit = args.Cancel;
                        f.Close();
                    }

                    if (cancelExit) break;
                }

                if (cancelExit) return;

                Process.Start(new ProcessStartInfo
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = Application.ExecutablePath,
                    Arguments = commandLine.Length > 0 ? string.Join(" ", commandLine) : string.Empty
                });

                Application.Exit();
            }
            finally
            {
                _exiting = false;
            }
        }
    }
查看更多
在下西门庆
7楼-- · 2019-01-21 20:55

I use similar code to the code you tried when restarting apps. I send a timed cmd command to restart the app for me like this:

ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Application.Exit(); 

The command is sent to the OS, the ping pauses the script for 2-3 seconds, by which time the application has exited from Application.Exit(), then the next command after the ping starts it again.

Note: The \" puts quotes around the path, incase it has spaces, which cmd can't process without quotes.

Hope this helps!

查看更多
登录 后发表回答