Hoo*_*och 95
我发现了这个:它有效.但.有没有更好的方法?
System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
Application.Current.Shutdown();
Run Code Online (Sandbox Code Playgroud)
epa*_*alm 36
我在WPF中使用过这个,成功:
System.Windows.Forms.Application.Restart();
System.Windows.Application.Current.Shutdown();
Run Code Online (Sandbox Code Playgroud)
Pas*_*lsz 11
Application.Restart();
Run Code Online (Sandbox Code Playgroud)
要么
System.Diagnostics.Process.Start(Application.ExecutablePath);
Application.Exit();
Run Code Online (Sandbox Code Playgroud)
在我的程序中,我有一个互斥锁,以确保只有一个应用程序实例在计算机上运行.这导致新启动的应用程序无法启动,因为互斥锁未及时释放.因此,我在Properties.Settings中添加了一个值,表明应用程序正在重新启动.在调用Application.Restart()之前,Properties.Settings值设置为true.在Program.Main()中,我还添加了对特定property.settings值的检查,以便在为true时将其重置为false并且存在Thread.Sleep(3000);
在你的程序中,你可能有逻辑:
if (ShouldRestartApp)
{
Properties.Settings.Default.IsRestarting = true;
Properties.Settings.Default.Save();
Application.Restart();
}
Run Code Online (Sandbox Code Playgroud)
在Program.Main()中
[STAThread]
static void Main()
{
Mutex runOnce = null;
if (Properties.Settings.Default.IsRestarting)
{
Properties.Settings.Default.IsRestarting = false;
Properties.Settings.Default.Save();
Thread.Sleep(3000);
}
try
{
runOnce = new Mutex(true, "SOME_MUTEX_NAME");
if (runOnce.WaitOne(TimeSpan.Zero))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
finally
{
if (null != runOnce)
runOnce.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
而已.
mag*_*ode 10
在1秒延迟后通过命令行运行程序的新实例.在延迟当前实例关闭期间.
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C choice /C Y /N /D Y /T 1 & START \"\" \"" + Assembly.GetEntryAssembly().Location + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Process.GetCurrentProcess().Kill();
Run Code Online (Sandbox Code Playgroud)
Application.Current.Shutdown();
System.Windows.Forms.Application.Restart();
Run Code Online (Sandbox Code Playgroud)
按照这个顺序为我工作,反过来只是启动了另一个应用程序实例.
这些提议的解决方案可能有效,但正如另一位评论者所提到的,它们感觉有点像快速破解。另一种感觉更简洁的方法是运行一个批处理文件,其中包含延迟(例如 5 秒)以等待当前(关闭)应用程序终止。
这可以防止两个应用程序实例同时打开。在我的情况下,同时打开两个应用程序实例是无效的 - 我使用互斥锁来确保只有一个应用程序打开 - 由于应用程序使用了一些硬件资源。
示例 Windows 批处理文件(“restart.bat”):
sleep 5
start "" "C:\Dev\MyApplication.exe"
Run Code Online (Sandbox Code Playgroud)
在 WPF 应用程序中,添加以下代码:
// Launch the restart batch file
Process.Start(@"C:\Dev\restart.bat");
// Close the current application
Application.Current.MainWindow.Close();
Run Code Online (Sandbox Code Playgroud)