c#守护进程(windows服务监测程序,程序关闭后自启动)最详细!!!!!!!!

本文详细介绍如何创建一个Windows服务,该服务能在程序关闭后自动重启,包括实现步骤、所需DLL及代码示例,适用于希望保持程序持续运行的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目需要:程序关闭后自动重新启动,需要一个监测程序所以写下这篇文章,为自己以后留个印象,也给大家一个参考,不喜勿喷!!!

1.打开VS创建windows服务

 2.实现服务的操作步骤(查看service1代码)

 3.(右键)添加引用(这个dll是为显示界面的,很多人说windows服务开启了,程序也在运行就是不显示界面那就需要这个了)

下载地址: 链接:https://pan.baidu.com/s/1R2AFVxLArZCkwCumlUxN1w 密码:4qhn

记得添加命名空间!!!

引用dll需要用到的代码

 try
            {
                //appStartPath = "程序路径";
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)System.Runtime.InteropServices.Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {

            }

4.在对应位置写入代码

protected override void OnStart(string[] args)
       {
           //服务开启执行代码
       }
       protected override void OnStop()
       {
           //服务结束执行代码
       }
       protected override void OnPause()
       {
           //服务暂停执行代码
           base.OnPause();
       }
       protected override void OnContinue()
       {
           //服务恢复执行代码
           base.OnContinue();
       }
       protected override void OnShutdown()
       {
           //系统即将关闭执行代码
           base.OnShutdown();
       }

全部代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Cjwdev.WindowsApi;

namespace process
{
    public partial class Service1 : ServiceBase
    {
        string appStartPath = @"C:\Users\Administrator\Desktop\okl1\okl1.exe";
        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
           // string appStartPath= @"C:\Users\Administrator\Desktop\okl1\okl1.exe";
            System.Timers.Timer timer;
           
            timer = new System.Timers.Timer();
            timer.Interval = 10000;//设置计时器事件间隔执行时间
            timer.Elapsed += new System.Timers.ElapsedEventHandler(circulation);
            timer.Enabled = true;
        }
        protected override void OnStop()
        {
        }
        private void circulation(object sender,System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //appStartPath = "程序路径";
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)System.Runtime.InteropServices.Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }
            catch (Exception ex)
            {

            }
            string appName = "okl1";//the path of the exe file
            bool runFlag = false;
            Process[] myProcesses = Process.GetProcesses();
            foreach (Process myProcess in myProcesses)
            {
                if (myProcess.ProcessName.CompareTo(appName) == 0)
                {
                    runFlag = true;
                }

            }

            if (!runFlag)   //如果程序没有启动
            {
                Process proc = new Process();
                proc.StartInfo.FileName = appName;
                proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(appStartPath);
                proc.Start();


            }
        }
    }
}

5.添加安装程序

在services1的设计界面右键,选择添加安装程序:

生成serviceInstaller1和 serviceProcessInstaller1两个组件 。

6.把serviceInstaller1的属性ServiceName改写为你的服务程序名,并把启动模式设置为AUTOMATIC

7.把serviceProcessInstaller1的属性account改写为 LocalSystem

8.通过从生成菜单中选择生成来生成项目
安装卸载Windows服务

现在你所需要的代码写完之后点击运行是运行不了的!!!

9.安装windows服务

1.InstallUtil.exe存在路径为:C:\WINDOWS\Microsoft.NET\Framework\.NET版本号\InstallUtil.exe

2.找到它把它复制到你的项目中的bin\Debug或者bin\Release下

3.打开cmd输入命令runas /user:Administrator cmd                     输入密码(不知道的自己百度吧)

4.获得更高权限,避免后续权限不够出问题

5.输入安装命令比如:C:\Windows\system32>xxx\xxx\bin\Debug\InstallUtil.exe 空格 服务名.exe

6.安装成功之后:控制面板>管理工具>计算机管理>服务和应用程序>服务>找到你的服务开启就ok了

卸载Windows服务

输入命令:C:\Windows\system32>xxx\xxx\bin\Debug\InstallUtil.exe 空格 服务名.exe/u     就是多了个/u

如果修改这个服务,但是路径没有变化的话是不需要重新注册服务的,直接停止服务,然后用新的文件覆盖原来的文件即可,如果路径发生变化,应该先卸载这个服务,然后重新安装这个服务。

转载请注明出处

作者:Struggle_Cxg
来源:CSDN
原文:https://blog.csdn.net/Struggle_Cxg/article/details/83302251
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值