本文描述了一个用C#实现的简单的Windows Service。
功能是在启动和停止服务的时候,在Windows事件查看器(Event Log)里添加一条log。
在Visual Studio 2008中建立Windows Service项目之后,会自动生成一个Service1的服务,它的名字默认是Service1,我先把它的文件名从Service1.cs改成ITSTestService.cs,然后需要在ITSTestService.cs的设计器视图的属性里,把Service Name改成ITSTestService,不然添加完服务后,启动服务时会报出这样的错误:
由于下列错误,ITS Test Service 服务启动失败:
配置成在该可执行程序中运行的这个服务不能执行该服务。
安装服务
sc create ITSTestService binpath= "PATH TO SERVICE EXE" type= share start= auto displayname= "ITS Test Service"
卸载服务
sc delete ITSTestService
因为服务安装的名字是Service1。
1
using System; 2
using System.Collections.Generic; 3
using System.ComponentModel; 4
using System.Data; 5
using System.Diagnostics; 6
using System.ServiceProcess; 7
using System.Text; 8
9
namespace WindowsServiceHowto 10


{ 11
public partial class ITSTestService : ServiceBase 12

{ 13
public ITSTestService() 14

{ 15
InitializeComponent(); 16
} 17
18
protected override void OnStart(string[] args) 19

{ 20
WriteLog("ITSTestService Started."); 21
} 22
23
protected override void OnStop() 24

{ 25
WriteLog("ITSTestService Stopped."); 26
} 27
28
private void WriteLog(string eventString) 29

{ 30
string source; 31
string log; 32
source = "ITS Test Windows Service"; 33
log = "Application"; 34
35
if (!EventLog.SourceExists(source)) 36

{ 37
EventLog.CreateEventSource(source, log); 38
} 39
40
EventLog.WriteEntry(source, eventString); 41
} 42
} 43
}
源代码 :下载
转载于:https://www.cnblogs.com/Impulse/archive/2008/09/10/1288358.html