WPF实现软件重启

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);
}
原文地址:https://www.cnblogs.com/xhubobo/p/15791198.html