一步步开发Windows服务(Windows Service)[转]

基于0起步来创建一个服务,做到简单的记录时间日志功能,其具体招行方法可自行添加。

1.创建服务

2.删除默认服务文件

3.添加自己的服务文件

4.更改启动项目

5. 引用 using System.Timers;并添加FileClass类

FileClass类

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

6. 添加上步中需要的InitService()方法

复制代码
/// <summary>
        /// 初始化服务参数
        /// </summary>
        private void InitService()
        {
            base.CanShutdown = true;
            base.CanStop = true;
            base.CanPauseAndContinue = true;
            this.ServiceName = MainService.serviceName;
            this.AutoLog = false;//为了使用自定义日志,必须将 AutoLog 设置为 false

            tim = new System.Timers.Timer();
            tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
            tim.Interval = 5000;
            tim.AutoReset = true;
        }
复制代码

7. 解决System不包含windows属性问题,引用程序集。

8.添加上面引用 的 tim_Elapsed 定时方法

复制代码
 private void tim_Elapsed(object sender, EventArgs e)
        {
            StartThread();
        }

        /// <summary>  
        /// 开始任务 
        /// </summary>  
        private void StartThread()
        {
            MessageAdd(serviceName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        /// <summary>  
        ///  日志记录
        /// </summary>  
        /// <param name="serviceName">内容</param>  
        public void MessageAdd(string str)
        {
            try
            {
                fileclass.WriteLogFile(logPath, str);//写入记录日志
            }
            catch
            {

            }
        }
复制代码

9.此时生成解决方案是成功的

10.在OnStart等中写入自己的方法,这里用日志记录

复制代码
   protected override void OnStart(string[] args)
        {
            try
            {
                this.tim.Enabled = true;
                this.tim.Start();
            }
            catch (Exception ex)
            {
                MessageAdd("OnStart错误:" + ex.Message);
            }
            MessageAdd(serviceName + "已成功启动!");
        }

        protected override void OnStop()
        {
            try
            {
                this.tim.Stop();
            }
            catch (Exception ex)
            {
                MessageAdd("OnStop错误:" + ex.Message);
            }
            MessageAdd(serviceName + "已停止!");
        }

        protected override void OnContinue()
        {
            this.tim.Start();
            base.OnContinue();
        }

        protected override void OnPause()
        {
            this.tim.Stop();
            base.OnPause();
        }
复制代码

11.给服务添加安装程序。右键鼠标单击MainService.cs[设计]*选项卡选项“添加安装程序”。

12.可以看见项目中多了如下文件和组件,serviceProcessInstaller1、serviceInstaller1是自动生成的

13.设置组件serviceInstaller1的主要属性,StartType: AutoMatic自动启动;ServiceName: 服务系统标识,在cmd命令中执行sr start/stop/query等等命令时候使用,用来唯一标识一个Window服务

 

14.设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;

15.设置服务安装后“允许和桌面进行交互”,

需要在ProjectInstaller.cs中添加如下代码。

复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;


namespace TerminalTrance
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        protected override void OnAfterInstall(IDictionary savedState)
        {

            try
            {

                base.OnAfterInstall(savedState);

                // 允许服务桌面交互

                System.Management.ManagementObject myService = new System.Management.ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName));

                System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change");

                changeMethod["DesktopInteract"] = true;

                System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null);

            }

            catch (Exception ex)
            {

            }

        }
    }
}
复制代码

16.Windows服务的安装和卸载

代码写完后,编译通过后,就可以安装、卸载、调试服务了。

在执行安装或卸载服务前,我有把服务需要的相关文件,复制到C:\Service\下面或其他路径。一旦安装完成后,此目录不能变更,否则不能卸载该服务和服务运行会报错。

安装、卸载很简单,只要在VS命令行导航到,服务程序的路径。然后运行以下命令就OK了。

打开如图:

安装服务:installutil C:\Service\TerminalTrance.exe

卸载服务:installutil /u C:\Service\TerminalTrance.exe

调试的话,只能先安装启动服务,然后将该服务附加到进程,就可以调试了。安装好服务后,就可以在win7服务管理里面,管理刚刚启动的服务了。

 安装成功后可在服务中看到

 在服务程序中可以看到添加的服务

可以看到程序的日志记录

另外一个方法是生成安装exe程序

1.解决方案右键=》新建项目=》选择安装程序

2.安装项目右键=》添加=》项目输出,选择主项目

3.安装项目右键=》视图=》自定义操作

4.自定义操作=》安装右键=》选择主输出

5.卸载右键=》选择主输出

6.若有文件需要添加到安装后的文件夹中=》点击应用程序文件夹=》添加=》文件,选择文件。安装后就会生成指定文件。

7.生成程序,完成,Setup文件夹中找到exe安装文件执行就 OK了。卸载也是执行此exe,按提示下一步就OK。

作者: 欢醉
公众号【一个码农的日常】 技术群:319931204 1号群: 437802986 2号群: 340250479
出处: http://zhangs1986.cnblogs.com/
码云: https://gitee.com/huanzui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 

完成开发后,对整各项目进行编译生成。在windows服务开发文件夹“\bin\Debug”下,就是我们需要安装的服务,建议把里面的所有文件拷贝至系统里的某个目录进行安装。

  我是把整个个文件夹里的文件拷贝到c:\WindowService文件夹下。然后打开目录C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷贝里面的InstallUtil.exe文件至c:\WindowService文件夹下)。

  注意:我的系统是windows10,64位系统,我的服务也将安装至64位系统下,所以我是进入C:\Windows\Microsoft.NET\Framework64\v4.0.30319目录拷贝InstallUtil.exe文件。各位安装的时候,根据你安装的目标系统,来觉得是拷贝哪个framework哪个版本,具体是64位的还是32位的也由你系统决定。

  做好以上工作后就可以安装了,打开cdm就可执行安装了(一定要以管理员身份运行哟,要不然安装时会报“Windows服务安装异常:System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件”)。

  以下是安装命令、启动服务命令、停止服务命令、卸载服务命令:

    安装命令:C:\WindowService\InstallUtil.exe C:\WindowService\OrganizClientSocketService.exe 

    启动服务命令:net start 搜才Organiz客户端数据同步服务

    关闭服务命令:net stop 搜才Organiz客户端数据同步服务

    卸载服务命令:C:\WindowService\InstallUtil.exe -u C:\WindowService\OrganizClientSocketService.exe

基于0起步来创建一个服务,做到简单的记录时间日志功能,其具体招行方法可自行添加。

1.创建服务

2.删除默认服务文件

3.添加自己的服务文件

4.更改启动项目

5. 引用 using System.Timers;并添加FileClass类

FileClass类

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

6. 添加上步中需要的InitService()方法

复制代码
/// <summary>
        /// 初始化服务参数
        /// </summary>
        private void InitService()
        {
            base.CanShutdown = true;
            base.CanStop = true;
            base.CanPauseAndContinue = true;
            this.ServiceName = MainService.serviceName;
            this.AutoLog = false;//为了使用自定义日志,必须将 AutoLog 设置为 false

            tim = new System.Timers.Timer();
            tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
            tim.Interval = 5000;
            tim.AutoReset = true;
        }
复制代码

7. 解决System不包含windows属性问题,引用程序集。

8.添加上面引用 的 tim_Elapsed 定时方法

复制代码
 private void tim_Elapsed(object sender, EventArgs e)
        {
            StartThread();
        }

        /// <summary>  
        /// 开始任务 
        /// </summary>  
        private void StartThread()
        {
            MessageAdd(serviceName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        /// <summary>  
        ///  日志记录
        /// </summary>  
        /// <param name="serviceName">内容</param>  
        public void MessageAdd(string str)
        {
            try
            {
                fileclass.WriteLogFile(logPath, str);//写入记录日志
            }
            catch
            {

            }
        }
复制代码

9.此时生成解决方案是成功的

10.在OnStart等中写入自己的方法,这里用日志记录

复制代码
   protected override void OnStart(string[] args)
        {
            try
            {
                this.tim.Enabled = true;
                this.tim.Start();
            }
            catch (Exception ex)
            {
                MessageAdd("OnStart错误:" + ex.Message);
            }
            MessageAdd(serviceName + "已成功启动!");
        }

        protected override void OnStop()
        {
            try
            {
                this.tim.Stop();
            }
            catch (Exception ex)
            {
                MessageAdd("OnStop错误:" + ex.Message);
            }
            MessageAdd(serviceName + "已停止!");
        }

        protected override void OnContinue()
        {
            this.tim.Start();
            base.OnContinue();
        }

        protected override void OnPause()
        {
            this.tim.Stop();
            base.OnPause();
        }
复制代码

11.给服务添加安装程序。右键鼠标单击MainService.cs[设计]*选项卡选项“添加安装程序”。

12.可以看见项目中多了如下文件和组件,serviceProcessInstaller1、serviceInstaller1是自动生成的

13.设置组件serviceInstaller1的主要属性,StartType: AutoMatic自动启动;ServiceName: 服务系统标识,在cmd命令中执行sr start/stop/query等等命令时候使用,用来唯一标识一个Window服务

 

14.设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;

15.设置服务安装后“允许和桌面进行交互”,

需要在ProjectInstaller.cs中添加如下代码。

复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;


namespace TerminalTrance
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        protected override void OnAfterInstall(IDictionary savedState)
        {

            try
            {

                base.OnAfterInstall(savedState);

                // 允许服务桌面交互

                System.Management.ManagementObject myService = new System.Management.ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName));

                System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change");

                changeMethod["DesktopInteract"] = true;

                System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null);

            }

            catch (Exception ex)
            {

            }

        }
    }
}
复制代码

16.Windows服务的安装和卸载

代码写完后,编译通过后,就可以安装、卸载、调试服务了。

在执行安装或卸载服务前,我有把服务需要的相关文件,复制到C:\Service\下面或其他路径。一旦安装完成后,此目录不能变更,否则不能卸载该服务和服务运行会报错。

安装、卸载很简单,只要在VS命令行导航到,服务程序的路径。然后运行以下命令就OK了。

打开如图:

安装服务:installutil C:\Service\TerminalTrance.exe

卸载服务:installutil /u C:\Service\TerminalTrance.exe

调试的话,只能先安装启动服务,然后将该服务附加到进程,就可以调试了。安装好服务后,就可以在win7服务管理里面,管理刚刚启动的服务了。

 安装成功后可在服务中看到

 在服务程序中可以看到添加的服务

可以看到程序的日志记录

另外一个方法是生成安装exe程序

1.解决方案右键=》新建项目=》选择安装程序

2.安装项目右键=》添加=》项目输出,选择主项目

3.安装项目右键=》视图=》自定义操作

4.自定义操作=》安装右键=》选择主输出

5.卸载右键=》选择主输出

6.若有文件需要添加到安装后的文件夹中=》点击应用程序文件夹=》添加=》文件,选择文件。安装后就会生成指定文件。

7.生成程序,完成,Setup文件夹中找到exe安装文件执行就 OK了。卸载也是执行此exe,按提示下一步就OK。

猜你喜欢

转载自www.cnblogs.com/keepee/p/12499701.html