Restart an application by itself

后端 未结 10 627
醉话见心
醉话见心 2020-12-13 02:46

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

ProcessStartInfo Info=new ProcessStartInfo();
Info.Arguments=\"/C          


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 03:25

    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
    openForms = Application.OpenForms.OfType().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; } } }

提交回复
热议问题