WPF中通過System.Windows.Forms.Application.Restart方法可以實現軟件重啟,處理好重啟條件就能實現預期的重啟效果。
重啟條件可以存儲在Properties.Settings中,也可以存在於xml等配置文件中,甚至可以存在於SQLite等數據庫中,在需要重啟的時候將重啟標識設置為true,程序退出時判斷該標識為true就執行重啟方法,而在程序啟動后重置該標識為false。
1、用戶注銷時設置重啟標識
//設置重啟標記 _configService.AppRestart = true; Close();
2、程序退出時判斷重啟標識
protected override void OnExit(ExitEventArgs e) { base.OnExit(e); //重啟應用 if (configService.AppRestart) { if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1) { //Restart application in Win7 or lower OS var location = System.Reflection.Assembly.GetExecutingAssembly().Location; location = location.Replace(".dll", ".exe"); Process.Start(location); } else { System.Windows.Forms.Application.Restart(); } } }
3、程序啟動后重置重啟標識
protected override void OnStartup(StartupEventArgs e) { configService.AppRestart = false; base.OnStartup(e); }