【C#】Windows服务(Service)安装及启停

目录

一、创作背景

二、问题解决

2.1 安装Windows service服务

2.2 主方法Main()主方法改写

2.3 安装service服务/卸载service服务

2.4 服务启停

2.5 服务调用运行

2.6 关于权限的提升

三、资源分享

3.1 引入组件

3.2 新手使用


一、前言

我能抽象出整个世界,但是我不能抽象你。 想让你成为私有常量,这样外部函数就无法访问你。 又想让你成为全局常量,这样在我的整个生命周期都可以调用你。 可惜世上没有这样的常量,我也无法定义你,因为你在我心中是那么的具体。

哈喽大家好,本专栏为【项目实战】专栏,有别于【底层库】专栏,我们可以发现增加 了『问题描述』、『项目展示』章节,十分符合项目开发流程,让读者更加清楚项目解决的问题、以及产品能够达到的效果。本专栏收纳项目开发过程的解决方案,是我项目开发相对成熟、可靠方法的提炼,我将这些问题的解决思路梳理,撰写本文分享给大家,大家遇到类似问题,可按本文方案处理。

本专栏会持续更新,不断完善,专栏文章关联性较弱(文章之间依赖性较弱,没有阅读顺序)。大家有任何问题,可以私信我。如果您对本专栏感兴趣,欢迎关注吧,我将带你用最简洁的代码,实现复杂的功能。
 

二、创作背景

今天,我们完成了一个应用程序的开发,我们要将其设置成开机自启程序,继上篇文章介绍有两种方式。

一种,开机启动目录下创建应有程序的快捷方式;

另一种,写Windows服务;我们现在采用“服务方式自启程序”。

因为用户不具备管理员权限,为了安全考虑,我们方便监控管理。最终确认方案二。

先说说我们面临的问题,或者说是待解决的问题:

①安装服务,通过咱新开发的C#应用软件安装,不希望借助第三方工具(installutil.exe),因为面向人群非科班出身,操作越简单越好。

②开启、停止服务,不希望出现【黑色命令框】弹窗,看着就烦,用户体验不好。

③不希望出现Windows权限不够的提示框,因为用户是普通用户,不具备“管理员操作权限”,本程序有一些敏感操作,有需要最高权限,不要出现“权限不够,哪怕是否确认授权”消息提示框。

怎么样?需求是不是很变态,需要同时满足以上三点,网上很多技术教程已经不适用。变态需求即是挑战,下面我将介绍本文解决方案,彻底解决以上问题,希望可以帮助面临同样困状的你们。

三、解决方案

3.1 安装Windows service服务

点击【是否开机自启】,安装Windows service服务,并实现服务启停。

3.2 主方法Main()主方法改写

Program.cs文件Main()有两种运行方式

①客户端方式启动,最常用的方式,相当于鼠标双击可执行程序

②服务service方式启动,采用Windows service安装,默认含有参数。

因此我们可以通过参数args区分两种方式,如下图代码所示,其中客户端启动参用“单例模式”,我这里使用了全局信号量卡控,一次只能运行一个程序客户端。

 static void Main(string[] args)
        {
            //ProcessExec processExec = new ProcessExec();
            //string aa = "";
            //processExec.MediaServiceStart("", out aa);

            if (args.Length > 0)
            {
                var serviceName = Const.ct_strServiceName;
                var host = HostFactory.New(x =>
                {
                    x.EnableShutdown();
                    x.Service<ServiceCtrl>();
                    x.RunAsLocalSystem();
                    x.SetDescription(Const.ct_strProjName);
                    x.SetDisplayName(serviceName);
                    x.SetServiceName(serviceName);
                });
                LogHelper.Info("***********主程序运行(服务方式)**********");
                host.Run();
            }
            else
            {
                bool createNew;
                //使用用互斥量(System.Threading.Mutex)只运行一个实列
                using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
                {
                    if (createNew)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        LogHelper.Info("***********主程序运行(客户端方式)**********");
                        Application.Run(new FormMain());
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1000);
                        System.Environment.Exit(1);
                    }
                }
            }
            
    }

3.3 安装service服务/卸载service服务

①添加新项-->Windows服务--AutoPlayerService.cs

 ②右键空白处,【添加安装程序】,它会自动创建ProjectInstaller.cs文件,打开该文件有两个组件serviceProcessInstaller1、serviceInstaller1

网上大部分文章,教你们在属性中填写 服务信息,这种方式存在缺陷,常常服务不能够自动注入,需要借助第三方工具写入注册表,我教你们另外一种方式,如下图所示:

 ③我的方式,通过使用底层入口实现。

添加以下4行代码。

        [DllImport("kernel32.dll")]
        public static extern int WinExec(string CmdLine, int ShowCmd);

        [DllImport("shell32.dll")]
        public static extern int ShellExecute(IntPtr hWnd, string Operation, string FileName,
                                              string Parameters, string Directory, int ShowCmd);

 ④实现方法

安装服务

                string cmd = Application.ExecutablePath;
                cmd += " install";
                WinExec(cmd, 1);
                MessageBox.Show("服务安装完毕!");
                ShellExecute(this.Handle, "open", "Services.msc", "", "", 1);

卸载方法

                    ServiceStop(Const.ct_strServiceName);//停止服务
                    string cmd = Application.ExecutablePath;
                    cmd += " uninstall";
                    WinExec(cmd, 1);
                    MessageBox.Show("服务卸载完毕!");

3.4 服务启停

①创建服务类ServiceCtrl.cs ,实现接口ServiceControl。

  public class ServiceCtrl : ServiceControl
    {
        MainTimer m_MainTimer;

        public ServiceCtrl()
        {
            try
            {
                m_MainTimer = new MainTimer(21600);//6小时检查一次
                m_MainTimer.InitTimer();
            }
            catch (Exception err)
            {
                LogHelper.Error("初始化服务发生错误:" + err.ToString());
            }
        }

        /// <summary>
        /// 服务启动时执行
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public bool Start(Topshelf.HostControl c)
        {
            try
            {
                m_MainTimer.StartTimer();
                string l_strMsgError = "";
                if (SysParameter.shutdown_tag == "T")
                {
                    ProcessExec exec = new ProcessExec();
                    exec.StartShutDown(out l_strMsgError);
                }
                return true;
            }
            catch (Exception err)
            {
                LogHelper.Error("启动服务发生错误:" + err.ToString());
                return false;
            }
        }

        /// <summary>
        /// 服务关闭时执行
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public bool Stop(Topshelf.HostControl c)
        {
            try
            {
                m_MainTimer.StopTimer();
                return true;
            }
            catch (Exception err)
            {
                LogHelper.Error("停止服务发生错误:" + err.ToString());
                return false;
            }
        }
    }

②服务启动

        //启动服务
        public static void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

③服务停止

      //停止服务
        public static void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }

④判断服务是否在运行状态(可选)

        //判断服务状态
        public static bool IsServiceRuning(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }

3.5 服务调用运行

以上基本完成了服务的开发,关于服务调用我给一个案例:我这里鼠标右键点击,自动启动服务,开始执行主方法。

 //启动服务(Windows服务运行)
        private void BTN_ServiceRun_Click(object sender, EventArgs e)
        {
            m_service.Start(null);
            try
            {
                BTN_ServiceRun.Enabled = false;

                //ToDo:采用服务式,无dos黑框
                //string cmd = Const.ct_strServiceName;
                //cmd = "net start " + cmd;
                //FormSet.WinExec(cmd, 1);

                FormSet.ServiceStart(Const.ct_strServiceName);
                if (DataOperation.UpdateStateType("正在运行"))
                {
                    GC_Main.DataSource = DataOperation.SelectData();
                    GC_Main.RefreshDataSource();
                }
            }
            finally
            {
                BTN_ServiceStop.Enabled = true;
            }
        }

        //停止服务(Windows服务停止)
        private void BTN_ServiceStop_Click(object sender, EventArgs e)
        {
            m_service.Stop(null);
            try
            {
                BTN_ServiceStop.Enabled = false;

                FormSet.ServiceStop(Const.ct_strServiceName);
                if (DataOperation.UpdateStateType("已停止"))
                {
                    GC_Main.DataSource = DataOperation.SelectData();
                    GC_Main.RefreshDataSource();
                }
            }
            finally
            {
                BTN_ServiceRun.Enabled = true;
            }
        }

3.6 关于权限的提升

有时,你或许没有管理员权限,毕竟公司电脑嘛,每次服务开启都会有弹窗提示“权限不足”,很是厌烦,而且我们还要再次人工干预,这时你需要再程序中增加用户权限配置清单。

创建app.manifest应用程序清单文件。

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC 清单选项
             如果想要更改 Windows 用户帐户控制级别,请使用
             以下节点之一替换 requestedExecutionLevel 节点。n
        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
            如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
            元素。
        -->
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的
           Windows 版本的列表。取消评论适当的元素,
           Windows 将自动选择最兼容的环境。 -->

      <!-- Windows Vista -->
      <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->

      <!-- Windows 7 -->
      <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->

      <!-- Windows 8 -->
      <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->

      <!-- Windows 8.1 -->
      <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->

      <!-- Windows 10 -->
      <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->

    </application>
  </compatibility>

  <!-- 指示该应用程序可以感知 DPI 且 Windows 在 DPI 较高时将不会对其进行
       自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需
       选择加入。选择加入此设置的 Windows 窗体应用程序(目标设定为 .NET Framework 4.6 )还应
       在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。-->
  <!--
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
  </application>
  -->

  <!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) -->
  <!--
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
          type="win32"
          name="Microsoft.Windows.Common-Controls"
          version="6.0.0.0"
          processorArchitecture="*"
          publicKeyToken="6595b64144ccf1df"
          language="*"
        />
    </dependentAssembly>
  </dependency>
  -->

</assembly>

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />这句代码帮你以管理员身份运行,这样就不会弹窗了。

四、资源分享

4.1 引入组件

你需要引入最强大的组件库 Geyc.Utils.dll,我已经本文介绍的方法封装了,本组件包含大量实战项目的操作类、底层库、UI控件等,定期更新补充。

倘若你在项目引用过程中,发现组件中的错误,或是库不支持,或是组件适配环境性问题,请联系我修改封装底层库文件。

链接:https://pan.baidu.com/s/1sEO9aH2_re7Xwa-WDL_V7w?pwd=l6d0 
提取码:l6d0

4.2 新手使用

我已将方法封装,你也只需要几行代码就可以实现本文阐述的功能。

//判断服务是否运行
IsServiceRuning(string serviceName)

//安装服务
InstallService(string serviceFilePath)

//卸载服务
UninstallService(string serviceFilePath)

//启动服务
ServiceStart(string serviceName)

//停止服务
ServiceStop(string serviceName)

4.3 底层库源码

组件库 Geyc.Utils.dll中,你使用到的方法如下:

        [DllImport("kernel32.dll")]
        public static extern int WinExec(string CmdLine, int ShowCmd);

        [DllImport("shell32.dll")]
        public static extern int ShellExecute(IntPtr hWnd, string Operation, string FileName,
                                              string Parameters, string Directory, int ShowCmd);


     #region 开机自启项
        string serviceFilePath = Application.ExecutablePath;
        private void checkBox_AutoRun_CheckedChanged(object sender, EventArgs e)
        {
            if (!m_bStart) return;

            if (checkBox_AutoRun.Checked) //设置开机自启动  
            {
                string cmd = Application.ExecutablePath;
                cmd += " install";
                WinExec(cmd, 1);
                ShellExecute(this.Handle, "open", "Services.msc", "", "", 1);
                FrmTips.ShowTipsSuccess(this, "开机自启已启动!");

                AppConfig.SetValue("auto_run", "T");
            }
            else //取消开机自启动  
            {
                if (this.IsServiceExisted(Const.ct_strServiceName))
                {
                    ServiceStop(Const.ct_strServiceName);//停止服务
                    string cmd = Application.ExecutablePath;
                    cmd += " uninstall";
                    WinExec(cmd, 1);
                    FrmTips.ShowTipsSuccess(this, "开机自启已终止!");
                }
                AppConfig.SetValue("auto_run", "F");
            }
        }


        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        #region 安装服务/卸载服务
        //安装服务
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();//空参数
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        #endregion

        //判断服务状态
        public static bool IsServiceRuning(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }

        //启动服务
        public static void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //停止服务
        public static void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
        #endregion

 五、系列文章

C#项目--业务单据号生成器(定义规则、自动编号、流水号)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129129787

C#项目--开始日期结束日期范围计算(上周、本周、明年、前年等)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/129040663

C#项目--数据实体类使用
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816638

C#项目--单据审批流方案
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128972545

C#项目--二维码标签制作及打印(完整版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126884228

C#项目--条码管理操作手册
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126589496

C#项目--WebAPI发布和IIS部署,及异常处理
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126539836

C#项目--提高编程效率,代码自动生成
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126890673

C#项目--提高编程效率,Excel数据导入工具
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126427323

C#项目--Windows服务(Service)安装及启停方案
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124053794

C#项目--穿透Session隔离,服务调用外部程序(无窗体界面解决)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124053033

C#项目--任务计划实现,使用Quartz类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/123667723

C#项目--《周计划管理关于产前准备模块》解决方案20200203
本文链接:https://blog.csdn.net/youcheng_ge/article/details/122919543

C#项目--项目中,源码解析的正则表达式
本文链接:https://blog.csdn.net/youcheng_ge/article/details/118337074

C#项目--如何获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#项目--如何测试网络是否连通
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110137288

  • 6
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
C# Windows服务是一种在后台运行的应用程序,可以在Windows操作系统中作为服务安装和运行。Windows服务可以在系统启动时自动启动,并在后台持续运行,而不需要用户登录。它们通常用于执行一些长时间运行的任务或提供后台功能。 要创建一个C# Windows服务,你可以使用Visual Studio来创建一个新的Windows服务项目。在项目中,你可以编写代码来定义服务的行为和功能。在服务的主要代码中,你可以使用引用\[2\]中的方法来启动和停止服务。通过使用ServiceController类,你可以检查服务的状态并执行相应的操作。 例如,你可以使用引用\[3\]中的方法来判断服务是否在运行状态。这个方法会遍历系统中的所有服务,并检查每个服务的状态。如果找到了指定的服务,并且它的状态是运行中,那么就返回true,否则返回false。 在安装和卸载Windows服务时,你可以使用引用\[1\]中的命令行代码。这个命令行代码使用InstallUtil工具来安装或卸载服务。你需要提供服务的可执行文件路径和名称。 总之,C# Windows服务是一种在后台运行的应用程序,可以通过编写代码来定义其行为和功能。你可以使用ServiceController类来控制服务的启动、停止和状态检查。在安装和卸载服务时,你可以使用InstallUtil工具来执行相应的操作。 #### 引用[.reference_title] - *1* [Windows服务一:新建Windows服务安装、卸载服务](https://blog.csdn.net/weixin_34378969/article/details/85840546)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【C#Windows服务(Service)安装及启停](https://blog.csdn.net/youcheng_ge/article/details/124053794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花北城

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值