C#_创建Windows服务程序

1。新建一个Windows服务项目。

2。默认生成一个Service1.cs,更改其属性【ServiceName】为你需要显示在服务管理器中的服务名。注意,服务名长度不能超过80,不能包含“\\”和"\”。后台验证代码如下(感谢Reflector反编译工具):

internal static bool ValidServiceName(string serviceName)
{
    if (serviceName == null)
    {
        return false;
    }
    if ((serviceName.Length > 80) || (serviceName.Length == 0))
    {
        return false;
    }
    foreach (char ch in serviceName.ToCharArray())
    {
        switch (ch)
        {
            case '\\':
            case '/':
                return false;
        }
    }
    return true;
}

3.然后进入代码编辑窗口,默认会有两个重载的方法,你需要在这里编写你的服务代码:

//服务开启时
protected override void OnStart(string[] args)
{
    
}

//服务关闭时
protected override void OnStop()
{
   
}

 

4.然后,在设计窗口右键,点击【添加安装程序】,自动生成serviceInstaller1serviceProcessInstaller1两个组件。

serviceInstaller1的属性【ServiceName】改为之前设置的服务名,【StartType】改为"Automatic”。

serviceProcessInstaller1的属性【Account】改为“LocalSystem”。

5.最后,编译生成。

posted @ 2010-07-10 17:00  小 .xin  阅读(338)  评论(0编辑  收藏  举报
回到页首