c#编写Windows服务程序详细步骤详解(图文)

  

<强>一、创建一个Windows 服务

  

1)创建Windows 服务项目

  

 c#编写Windows服务程序详细步骤详解(图文)
  

  

 C #编写Windows服务程序详细步骤详解(图文),

  

2)对服务重命名

  

将Service1重命名为你服务名称,这里我们命名为ServiceTest。

  

<强>二,创建服务安装程序

  

1)添加安装程序

  

 C #编写Windows服务程序详细步骤详解(图文),

  

 C #编写Windows服务程序详细步骤详解(图文),

  

之后我们可以看到上图,自动为我们创建了ProjectInstaller.cs以及2个安装的组件。

  

2)修改安装服务名

  

右键serviceInsraller1,选择属性,将名的值改为ServiceTest。

  

 C #编写Windows服务程序详细步骤详解(图文),

  

3)修改安装权限

  

右键serviceProcessInsraller1,选择属性,将账户的值改为LocalSystem。

  

 C #编写Windows服务程序详细步骤详解(图文),

  

<强>三,写入服务代码

  

1)打开ServiceTest代码

  

右键ServiceTest,选择查看代码。

  

2)写入服务逻辑

  

添加如下代码:

        使用系统;   使用System.Collections.Generic;   使用System.ComponentModel;   使用System.Data;   使用System.Diagnostics;   使用来;   使用System.ServiceProcess;   使用text;   名称空间WindowsServiceTest   {   公共部分类ServiceTest: ServiceBase   {   公共ServiceTest ()   {   InitializeComponent ();   }   保护覆盖空白alt=" c#编写Windows服务程序详细步骤详解(图文)">,

  

1)安装

  

安装时会产生目录问题,所以安装代码如下:

        字符串CurrentDirectory=System.Environment.CurrentDirectory;   System.Environment。CurrentDirectory=CurrentDirectory +“\ \服务”;   过程过程=new过程();   process.StartInfo。UseShellExecute=false;   process.StartInfo。文件名=" Install.bat”;   process.StartInfo。CreateNoWindow=true;   process.Start ();   System.Environment。CurrentDirectory=CurrentDirectory;      

2)卸载

  

卸载时也会产生目录问题,所以卸载代码如下:

        字符串CurrentDirectory=System.Environment.CurrentDirectory;      System.Environment。CurrentDirectory=CurrentDirectory +“\ \服务”;   过程过程=new过程();   process.StartInfo。UseShellExecute=false;   process.StartInfo。文件名=" Uninstall.bat”;   process.StartInfo。CreateNoWindow=true;   process.Start ();   System.Environment。CurrentDirectory=CurrentDirectory;      

3)启动

  

代码如下:

        使用System.ServiceProcess;   ServiceController ServiceController=new ServiceController (“ServiceTest”);    serviceController.Start ();      

4)停止

        ServiceController ServiceController=new ServiceController (“ServiceTest”);   如果(serviceController.CanStop)    serviceController.Stop ();      

5)暂停/继续

        ServiceController ServiceController=new ServiceController (“ServiceTest”);   如果(serviceController.CanPauseAndContinue) {   如果(serviceController。状态==ServiceControllerStatus.Running)   serviceController.Pause ();   else if (serviceController。状态==ServiceControllerStatus.Paused)   serviceController.Continue ();   }      

6)检查状态

        ServiceController ServiceController=new ServiceController (“ServiceTest”);      字符串状态=serviceController.Status.ToString ();   之前      

<强>六、调试Windows 服务

  

1)安装并运行服务

  

2)附加进程

  

 c#编写Windows服务程序详细步骤详解(图文)

c#编写Windows服务程序详细步骤详解(图文)