一、打开Visual Studio,创建项目->Windows 服务(.NET Framework)
二、点击Service.cs 点击切换到代码视图
static Timer Timer; private Thread monitorThread; private static string logFilePath; private static Process winFormsProcess; public Service1(){InitializeComponent();logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");}protected override void OnStart(string[] args){// 启动监控线程monitorThread = new Thread(MonitorApplication);monitorThread.Start();// 设置定时器,每隔10秒检查一次目标应用程序是否退出Timer = new Timer(p => MonitorAndRestart(), null, TimeSpan.Zero, TimeSpan.FromSeconds(10));//启动目标程序StartTargetApplication();}static void MonitorAndRestart(){var targetProcessName = "FR"; // 替换为你的目标应用程序的进程名称var processes = Process.GetProcessesByName(targetProcessName);if (processes.Length == 0){Log("目标应用程序已退出,正在重新启动...");StartTargetApplication(); // 重新目标应用程序}}static void StartTargetApplication(){var targetProcessPath = @"D:\Debug\FR.exe"; // 替换为你的目标应用程序的路径var targetProcessStartInfo = new ProcessStartInfo(targetProcessPath){CreateNoWindow = false,UseShellExecute = true};winFormsProcess = Process.Start(targetProcessStartInfo);if (winFormsProcess != null){Log("目标程序已启动");}else{Log("目标程序启动失败");}}static void MonitorApplication(){var targetProcessName = "Service1"; // 替换为你的服务名称while (true){var processes = Process.GetProcessesByName(targetProcessName);if (processes.Length == 0){break;}Thread.Sleep(10000); // 每隔10秒检查一次}}//日志输入 文本文档static void Log(string message) {Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));if (!File.Exists(logFilePath)) {File.Create(logFilePath).Close();}using (var writer = new StreamWriter(logFilePath, true)) {writer.WriteLine($"{DateTime.Now.ToString()}{message}");}}protected override void OnStop(){Timer.Dispose();monitorThread.Join();Log("服务已停止,退出检控...");// 关闭 WinForms 项目if (winFormsProcess != null && !winFormsProcess.HasExited){winFormsProcess.CloseMainWindow();if (!winFormsProcess.WaitForExit(5000)){winFormsProcess.Kill();}}}
三、点击Service.cs 在Service.cs设计视图中右击添加安装程序
四、会出现一个serviceProcessInstaller1和serviceInstaller1两个组件,serviceInstaller1属性中的ServiceName是服务名可以修改成自己的,把serviceProcessInstaller1属性中的Account改为LocalSystem
五、重新生成一下项目
六、在项目的bin\Debug文件夹下添加文本文档名为InstallService然后写上以下代码,替换为你的服务的实际路径,然后把文本文档的后缀名改成bat(这是安装服务,要以管理员启动),这样就可以在服务中看见你自己写的服务了
installutil C:\Users\34349\Desktop\Anomalymonitoring\bin\Debug\Anomalymonitoring.exepause
七、在项目的bin\Debug文件夹下添加文本文档名为Uninstall然后写上以下代码,替换为你的服务的实际路径,然后把文本文档的后缀名改成bat(这是卸载服务,要以管理员启动)
installutil C:\Users\34349\Desktop\Anomalymonitoring\bin\Debug\Anomalymonitoring.exe /u
pause
注意:这个服务不能启动winfrom这种可视化项目