using System.Diagnostics; namespace ClassNotify.Setup.Services; public class WindowsServiceManager { public const string ServiceName = "ClassNotifyService"; public const string DisplayName = "ClassNotify Classroom Service"; public const string Description = "ClassNotify 教室大屏守护进程,负责维持与云端 SignalR 长连接及本地 IPC 通信。"; public static bool IsServiceInstalled() { var result = RunScCommand($"query {ServiceName}"); return result.ExitCode == 0 && !result.Output.Contains("1060", StringComparison.OrdinalIgnoreCase); } public static bool IsServiceRunning() { var result = RunScCommand($"query {ServiceName}"); return result.ExitCode == 0 && result.Output.Contains("RUNNING", StringComparison.OrdinalIgnoreCase); } public static void StopService() { if (IsServiceRunning()) { RunScCommand($"stop {ServiceName}"); for (int i = 0; i < 20; i++) { Thread.Sleep(500); if (!IsServiceRunning()) break; } } } public static void InstallAndStartService(string exePath) { if (IsServiceInstalled()) { StopService(); RunScCommand($"delete {ServiceName}"); Thread.Sleep(1000); } // 1. Create service using PowerShell New-Service for rock-solid path handling var psCommand = $"New-Service -Name '{ServiceName}' -BinaryPathName '\"{exePath}\"' -DisplayName '{DisplayName}' -StartupType Automatic"; var createResult = RunPowerShellCommand(psCommand); if (createResult.ExitCode != 0 && !createResult.Output.Contains("already exists", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"创建 Windows 服务失败: {createResult.Output}"); } // 2. Set description RunScCommand($"description {ServiceName} \"{Description}\""); // 3. Set failure recovery policy (Restart on crash: 5s, 10s, 60s, reset counter after 24h) var failureArgs = $"failure {ServiceName} reset= 86400 actions= restart/5000/restart/10000/restart/60000"; RunScCommand(failureArgs); // 4. Start service RunScCommand($"start {ServiceName}"); // Wait up to 10 seconds for service to enter Running state for (int i = 0; i < 20; i++) { Thread.Sleep(500); if (IsServiceRunning()) return; } if (!IsServiceRunning()) { throw new InvalidOperationException("服务已注册,但未能在 10 秒内成功启动,请检查系统事件日志。"); } } public static void UninstallService() { StopService(); RunScCommand($"delete {ServiceName}"); } private static (int ExitCode, string Output) RunScCommand(string arguments) { try { var psi = new ProcessStartInfo { FileName = "sc.exe", Arguments = arguments, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; using var process = Process.Start(psi); if (process == null) return (-1, "无法启动 sc.exe"); var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd(); process.WaitForExit(10000); return (process.ExitCode, output); } catch (Exception ex) { return (-1, ex.Message); } } private static (int ExitCode, string Output) RunPowerShellCommand(string script) { try { var psi = new ProcessStartInfo { FileName = "powershell.exe", Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{script}\"", CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; using var process = Process.Start(psi); if (process == null) return (-1, "无法启动 powershell.exe"); var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd(); process.WaitForExit(15000); return (process.ExitCode, output); } catch (Exception ex) { return (-1, ex.Message); } } }