修复重启和更新vbs无效问题

This commit is contained in:
蓝点lilac
2021-08-28 14:35:29 +08:00
parent 54cc4851e8
commit 48210df816

View File

@@ -42,69 +42,53 @@ namespace BluePointLilac.Methods
/// <summary>重启单实例程序</summary>
/// <param name="args">重启程序时传入参数</param>
/// <param name="updatePath">用于更新程序的新版本文件路径为null则不更新</param>
/// <param name="updatePath">用于更新程序的新版本文件路径为null则为普通重启</param>
public static void Restart(string[] args = null, string updatePath = null)
{
string appPath = Application.ExecutablePath;
string command = appPath;
if(args != null && args.Length > 0) command += "," + string.Join(" ", args);
List<string> contents = new List<string>();
using(Process pApp = Process.GetCurrentProcess())
//vbs命令逐行执行不等待故加些代码确定上一条命令执行是否完成
contents.AddRange(new[]
{
//Vbs命令逐行执行不等待故加些代码确定上一条命令执行是否完成
contents.AddRange(new[]{
"Dim wsh, fso, wmi, ps",
"Set wsh = CreateObject(\"WScript.Shell\")",
"Set fso = CreateObject(\"Scripting.FileSystemObject\")",
"fso.DeleteFile(WScript.ScriptFullName)",//vbs自删命令
$"wsh.Run \"taskkill /pid {pApp.Id} -f\",0",//杀死当前进程
"Dim isRun",
"Do",
"isRun = 0",
"WScript.Sleep 100",
"Set wmi = GetObject(\"WinMgmts:\")",
"Set ps = wmi.InstancesOf(\"Win32_Process\")",
//确定进程完全退出
"For Each p in ps",
$"If p.ProcessID = {pApp.Id} Then",
"isRun = 1",
"Exit For",
"End If",
"Next",
"Loop Until isRun = 0",
});
}
"On Error Resume Next",
"WScript.Sleep 1000",//等待程序结束
"Dim wsh, fso",
"Set wsh = CreateObject(\"WScript.Shell\")",
"Set fso = CreateObject(\"Scripting.FileSystemObject\")",
});
if(File.Exists(updatePath))
{
contents.AddRange(new[]
{
$"fso.DeleteFile \"{appPath}\"",
$"Do",
$"Do While fso.FileExists(\"{appPath}\")",
"WScript.Sleep 100",
"Loop Until fso.FileExists(\"{appPath}\") = False",//确定文件删除完成
"Loop",//确定文件删除完成
$"fso.MoveFile \"{updatePath}\",\"{appPath}\"",//更新文件
$"Do",
$"Do While fso.FileExists(\"{updatePath}\")",//确定文件已被移动
"WScript.Sleep 100",
$"Loop Until fso.FileExists(\"{appPath}\")",//确定文件存在
$"Loop",
});
}
contents.AddRange(new[]
{
$"wsh.Run \"{command}\"",
"fso.DeleteFile(WScript.ScriptFullName)",//vbs自删命令
"Set wsh = Nothing",
"Set fso = Nothing",
"Set wmi = Nothing",
"Set ps = Nothing",
});
string vbsPath = Path.GetTempPath() + Guid.NewGuid() + ".vbs";
File.WriteAllLines(vbsPath, contents.ToArray(), Encoding.Unicode);
using(Process pVbs = new Process())
Application.Exit();
using(Process process = new Process())
{
pVbs.StartInfo.FileName = "wscript.exe";
pVbs.StartInfo.Arguments = vbsPath;
pVbs.Start();
process.StartInfo.FileName = "wscript.exe";
process.StartInfo.Arguments = vbsPath;
process.Start();
}
}
}