(转)C#创建windows服务

原文地址:http://blog.itpub.net/23109131/viewspace-688117/

第一步:创建服务框架

创建一个新的 Windows 服务项目,可以从Visual C# 工程中选取 Windows 服务(Windows
Service)选项,给工程一个新文件名,然后点击确定。现在项目中有个Service1.cs类:

查看其各属性的含意是:

Autolog                    
   
 是否自动写入系统的日志文件
        
CanHandlePowerEvent    
 服务时候接受电源事件
        
CanPauseAndContinue    
服务是否接受暂停或继续运行的请求
         CanShutdown
               
服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown
过程
         CanStop    
                 
 服务是否接受停止运行的请求
        
ServiceName                
 服务名

第二步:向服务中增加功能 
在 .cs代码文件中我们可以看到,有两个被忽略的函数
OnStart和OnStop。

OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。这个例子是:当启动和停止服务时,定时显示“hello,你好”;

首先在Service1.cs设计中拖个timer控件,设置好它的Interval=60000,与要做的功能

代码如下:

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//OnStart函数在启动服务时执行

 protected
override void OnStart(string[] args)

 {

     this.timer1.Start();

 }

// OnStop函数在停止服务时执行

 protected
override void OnStop()

 {

     this.timer1.Stop();

 }

 private
void timer1_Tick(object
sender, EventArgs e)

 {

      System.Diagnostics.Process.Start("http://www.baidu.com");

 }  

 第三步: 将安装程序添加到服务应用程序

1:在解决方案中,右击服务Service1.cs设计视图。

2:在属性窗口中,单击-添加安装程序

这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件
ServiceProcessInstaller 和 ServiceInstaller,并且服务的属性值被复制到组件。

3:若要确定如何启动服务,请单击 ServiceInstaller 组件并将 StartType 属性设置为适当的值。

Manual      服务安装后,必须手动启动。

Automatic   
每次计算机重新启动时,服务都会自动启动。

Disabled     服务无法启动。

4:将serviceProcessInstaller类的Account属性改为 LocalSystem

这样,不论是以哪个用户登录的系统,服务总会启动。

第四步:生成服务程序

通过从生成菜单中选择生成来生成项目shift+F6。或重新生成项目注意   不要通过按 F5
键来运行项目——不能以这种方式运行服务项目。

第五步:服务的安装与卸载

访问项目中的已编译可执行文件所在的目录。 
用项目的输出作为参数,从命令行运行
InstallUtil.exe。在命令行中输入下列代码: 
installutil WindowsService1.exe

卸载服务 
用项目的输出作为参数,从命令行运行 InstallUtil.exe。

installutil /u WindowsService1.exe

附:installutil.exe
在安装VS电脑的C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe 
到vs2008命令提示符下installutil.exe
/?可以查看其帮助说明

推荐的另一中安装服务的方法
 用winform来调用安装,当点击按钮时,安装服务.
1.项目需要添加引用System.Configuration.Install和System.ServiceProcess

代码如下:
using System.Configuration.Install;
using
System.ServiceProcess;
/// <summary>   
  
/// 安装服务   
   ///
</summary>   
   private void
btnInstall_Click(object sender, EventArgs e)   
  
{   
         string[]
args = { "WindowsService1.exe"
};
           //卸载服务
string[] args = {"/u",
"WindowsService1.exe"};  
           
if
(!ServiceIsExisted("Service1"))//这里的Service1是对应真实项目中的服务名称
           
{
               
try
               
{
                   
ManagedInstallerClass.InstallHelper(args);  //参数 args 就是你用 InstallUtil.exe
工具安装时的

参数。一般就是一个exe的文件名 
               
}
               
catch (Exception
ex)
               
{
                   
MessageBox.Show(ex.Message);
                   
return;
               
}
           
}
           
else
           
{
               
MessageBox.Show("该服务已经存在,不用重复安装。");
           
}
   }

/// <summary>   
///
检查指定的服务是否存在。   
/// </summary>   
///
<param name="serviceName">要查找的服务名字</param>   
///
<returns></returns>   
private bool
ServiceIsExisted(string
svcName)   
{   
   
ServiceController[] services =
ServiceController.GetServices();   
    foreach
(ServiceController s in services)   
   
{   
        if
(s.ServiceName ==
svcName)   
       
{   
           
return true;   
       
}   
   
}   
    return
false;   
}

通过System.Configuration.Install.ManagedInstallerClass 类中的静态方法
InstallHelper就可以实现手工安装。 该方法的

签名如下: 
public static void InstallHelper(string[] args) 
其中参数
args 就是你用 InstallUtil.exe 工具安装时的参数。一般就是一个exe的文件名

第六步:调试服务

安装后,服务不会自动启动,服务不可以与桌面交互

1.设置服务安装后自动启动
添加serviceInstaller1的AfterInstall事件

?





1

2

3

4

5

6

using
System.Diagnostics;

private
void serviceInstaller1_AfterInstall(object
sender, InstallEventArgs e)

{

    System.ServiceProcess.ServiceController s = new
System.ServiceProcess.ServiceController("Service1");

    s.Start();//设置服务安装后立即启动

}

2.设置允许服务与桌面交互方法

让服务启动某个应用程序,就要修改服务的属性,勾选允许服务与桌面交互,#region 设置服务与桌面交互

?





1

2

3

4

5

6

7

8

9

10

11

12

/// <summary>

/// 设置服务与桌面交互,在serviceInstaller1的AfterInstall事件中使用

/// </summary>

/// <param name="serviceName">服务名称</param>

private
void SetServiceDesktopInsteract(string
serviceName)

{

 System.Management.ManagementObject wmiService = new  
System.Management.ManagementObject(string.Format

  ("Win32_Service.Name=‘{0}‘", serviceName));

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

    changeMethod["DesktopInteract"] = true;

    System.Management.ManagementBaseObject utParam = wmiService.InvokeMethod("Change", changeMethod,null<br>);

  }<br>#endregion 

3.windows服务是不执行Timer控件的,解决办法
把上面用到的Timer控件清除
public
Service1()
       
{
           
InitializeComponent();

System.Timers.Timer t = new
System.Timers.Timer();
           
t.Interval
=1000*15;
           
t.Elapsed += new
System.Timers.ElapsedEventHandler(RunWork);
           
t.AutoReset =
true;//设置是执行一次(false),还是一直执行(true);
           
t.Enabled = true;//是否执行

}

public void RunWork(object source, System.Timers.ElapsedEventArgs
e)
       

          
//要定时处理的事情
         
//这样服务就可以定时执行任务了
        }

总结:windows服务编程
1.服务不会执行Timer控件
2.默认服务安装完成后,是不会自动启动,不能与桌面交互
3.安装服务时,推荐新建个winform项目,用winform项目来执行服务的安装与卸载
4.OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。
5.右击-将服务添加到应用程序

时间: 2024-08-08 10:12:49

(转)C#创建windows服务的相关文章

Topshelf创建Windows服务

使用Topshelf创建Windows服务 概述 Topshelf是创建Windows服务的另一种方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf通过5个步骤详细的介绍使用使用Topshelf创建Windows 服务.Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主. 引用安装 1.官网:http://topshelf-project.c

使用Topshelf 5步创建Windows 服务 z

使用Topshelf创建Windows 服务简要的介绍了创建Windows服务的另一种方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf通过5个步骤详细的介绍使用使用Topshelf创建Windows 服务.Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主. 1.Topshelf的代码托管在http://topshelf-project.c

(转)创建Windows服务(Windows Services)N种方式总结

转自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html 最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来.目前我知道的创建创建Windows服务有3种方式:a.利用.net框架类ServiceBaseb.利用组件Topshelfc.利用小工具instsrv和srvany 下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志: a.利用.net框架类

.Net创建windows服务入门

本文主要记录学习.net 如何创建windows服务. 1.创建一个Windows服务程序 2.新建安装程序 3.修改service文件 代码如下 protected override void OnStart(string[] args) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true)) { sw.WriteLine(DateTime.Now.ToString(&

在64位windows下使用instsrv.exe和srvany.exe创建windows服务

在64位windows下使用instsrv.exe和srvany.exe创建windows服务 在32位的windows下,包括windows7,windows xp以及windows 2003,都可以使用instsrv.exe和srvany.exe来创建自定义的windows服务.比如,我们有一个bat文件,用于将指定的程序作为服务进行启动,使用一般的工具都不可以进行此类工作,而使用由windows 2003的资源工具包windows toolkit中所带的instsrv就可以. 详细的用法这

创建Windows服务简单流程

1.首先打开VS2010(或者其他版本),创建Windows服务项目 2.创建完成后切换到代码视图,代码中默认有OnStart和OnStop方法执行服务开启和服务停止执行的操作,下面代码是详细解释: 注意选择的是系统时间,不是winform中的时间. using System; using System.IO; usingSystem.ServiceProcess; using System.Text; usingSystem.Timers; namespaceTestService { pub

使用Topshelf创建Windows 服务

本文转载:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html b.利用组件Topshelf 本方式特点:代码简单,开源组件,Windows服务可运行多个实例 Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com 第1步:引用程序集TopShelf.dll和log4net.dll 第2步:创

C#创建windows服务搭配定时器Timer使用实例(用代码做,截图版)

功能说明:C#创建一个windows服务,服务启动时D:\mcWindowsService.txt写入数据,服务运行期间每隔两秒写入当前时间.      原理这些就不说了,三语两语说不清楚,直接贴一个实例.不能贴图片!!那个压缩文里面是word文档!!有图有真相 1.建立空白项目 2.添加创建windows服务需要的引用,选择System.ServiceProcess.   3.创建服务类,继承ServiceBase,类的源代码在后面. 4. 添加windows服务的安装类. (1)在类名或者解

C#创建Windows服务与安装-图解

1.创建windows服务项目 2.右键点击Service1.cs,查看代码, 用于编写操作逻辑代码 3.代码中OnStart用于执行服务事件 public partial class Service1 : ServiceBase { string logFilePath = ""; LogHelper logHelper; WendyWuBll bll = new WendyWuBll(); public Service1() { logFilePath = Configuratio

PowerShell创建Windows服务

旧服务器要淘汰,上面的自定义的Windows服务要迁移: 一.创建服务 (1)将自定义的Windows服务所需要的文件复制到新服务器上: (2)使用powershell在新服务器上创建新的Windows服务,命令如下: new-service –Name OrderService –DisplayName OrderService –BinaryPathName "D:\order\OrderService.exe" –StartupType Automatic (3)检查创建成功: