using System;
|
using System.Collections.Generic;
|
using System.Diagnostics;
|
using System.IO;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using System.Windows;
|
|
namespace SmartScanner
|
{
|
public static class AppRestartHelper
|
{
|
private const string TaskName = "MyApp_Restart_Task";
|
|
public static async Task RestartAsync()
|
{
|
try
|
{
|
// 1. 创建临时批处理文件
|
string batPath = CreateRestartBatchFile();
|
|
// 2. 创建任务计划
|
CreateScheduledTask(batPath);
|
|
// 3. 延迟确保任务已注册
|
await Task.Delay(500);
|
|
// 4. 执行任务并退出当前实例
|
ExecuteRestartTask();
|
|
Application.Current.Shutdown();
|
}
|
catch (Exception ex)
|
{
|
MessageBox.Show($"重启失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
|
}
|
}
|
|
private static string CreateRestartBatchFile()
|
{
|
string tempPath = Path.GetTempPath();
|
string batPath = Path.Combine(tempPath, $"{Guid.NewGuid()}_restart.bat");
|
|
string exePath = Process.GetCurrentProcess().MainModule.FileName;
|
string workingDir = Path.GetDirectoryName(exePath);
|
|
string batContent = $@"
|
@echo off
|
timeout /t 1 /nobreak > nul
|
cd /d ""{workingDir}""
|
start """" ""{exePath}""
|
del ""%~f0""
|
";
|
|
File.WriteAllText(batPath, batContent);
|
return batPath;
|
}
|
|
private static void CreateScheduledTask(string batPath)
|
{
|
// 删除可能存在的旧任务
|
DeleteExistingTask();
|
|
// 创建新任务
|
ProcessStartInfo psi = new ProcessStartInfo
|
{
|
FileName = "schtasks.exe",
|
Arguments = $"/Create /TN \"{TaskName}\" /TR \"{batPath}\" /SC ONCE /ST {DateTime.Now.AddSeconds(1):HH:mm:ss} /F",
|
WindowStyle = ProcessWindowStyle.Hidden,
|
CreateNoWindow = true
|
};
|
|
Process.Start(psi)?.WaitForExit(2000);
|
}
|
|
private static void ExecuteRestartTask()
|
{
|
Process.Start(new ProcessStartInfo
|
{
|
FileName = "schtasks.exe",
|
Arguments = $"/Run /TN \"{TaskName}\"",
|
WindowStyle = ProcessWindowStyle.Hidden,
|
CreateNoWindow = true
|
})?.WaitForExit(1000);
|
|
// 删除任务
|
DeleteExistingTask();
|
}
|
|
private static void DeleteExistingTask()
|
{
|
Process.Start(new ProcessStartInfo
|
{
|
FileName = "schtasks.exe",
|
Arguments = $"/Delete /TN \"{TaskName}\" /F",
|
WindowStyle = ProcessWindowStyle.Hidden,
|
CreateNoWindow = true
|
})?.WaitForExit(1000);
|
}
|
}
|
}
|