用C#创建Windows服务(Windows Services)

学习:

 第一步:创建服务框架 
创建一个新的 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,与要做的功能
代码如下:

//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事件
using System.Diagnostics;
 private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {
           System.ServiceProcess.ServiceController s = new System.ServiceProcess.ServiceController("Service1");
            s.Start();//设置服务安装后立即启动
        }

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

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

#region 设置服务与桌面交互

/// <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);
        }
        #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.右击-将服务添加到应用程序

======================================================================

C# 创建Windows服务。服务功能:定时操作数据库

 

一、创建window服务

1、新建项目-->选择Windows服务。默认生成文件包括Program.cs,Service1.cs

2、在Service1.cs添加如下代码:

System.Timers.Timer timer1;  //计时器

public Service1()

{

InitializeComponent();

}

protected override void OnStart(string[] args)  //服务启动执行

{

timer1 = new System.Timers.Timer();

timer1.Interval = 3000;  //设置计时器事件间隔执行时间

timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);

timer1.Enabled = true;

}

protected override void OnStop()  //服务停止执行

{

this.timer1.Enabled = false;

}

private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

{

//执行SQL语句或其他操作

}

二、添加window服务安装程序

1、打开Service1.cs【设计】页面,点击右键,选择【添加安装程序】,会出现serviceInstaller1和serviceProcessInstaller1两个组件

2、将serviceProcessInstaller1的Account属性设为【LocalSystem】, serviceInstaller1的StartType属性设为【Automatic】,ServiceName属性可设置服务名称,此后在【管理工具】--》【服务】中即显示此名称

3、ProjectInstaller.cs文件,在安装服务后一般还需手动启动(即使上述StartType属性设为【Automatic】),可在ProjectInstaller.cs添加如下代码实现安装后自动启动

public ProjectInstaller()
        {
            InitializeComponent();
            this.Committed += new InstallEventHandler(ProjectInstaller_Committed);   
        }

private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
        {
            //参数为服务的名字
            System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服务名称");
            controller.Start();
        }

三、安装、卸载window服务

1、输入cmd(命令行),

4.0:cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

2.0:cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

2、安装服务(项目生成的exe文件路径)

InstallUtil "E:\WindowsService1\bin\Debug\WindowsService1.exe"

3、卸载服务

InstallUtil  /u "E:\WindowsService1\bin\Debug\WindowsService1.exe"

四、查看window服务

services.msc

控制面板-->管理工具-->服务,可在此手动启动,停止服务

五、调试window服务

1、通过【事件查看器】查看

2、直接在程序中调试(菜单-->调试-->附加进程-->服务名(这里的服务名是项目名称,不是ServiceName属性自定义的名称,所以建议自定义名称和项目名称保持一致,另外需勾选【显示所有用户的进程】才能看到服务名)-->附加

这里附加的进程名应该是:WindowsService1.exe 而不是 WindowsService1.vshost.exe。WindowsService1.exe 默认不会出现,必须勾选【显示所有用户的进程】【显示所有会话中的进程】

3. 在程序中打断点调试即可,另外调试服务时服务必须已启动(管理工具-->服务)

转自:http://blog.itpub.net/23109131/viewspace-688117/

用C#创建Windows服务(Windows Services)的更多相关文章

  1. C# windows服务:创建Windows服务(Windows Services)的一般步骤

    C#创建Windows服务(Windows Services) Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称.用Visual C# 创建Wind ...

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

    最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来.目前我知道的创建创建Windows服务有3种方式:a.利用.net框架类ServiceBaseb.利用组件Topshel ...

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

    转自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html 最近由于工作需要,写了一些windows服务程序,有一些经验,我现在 ...

  4. .net Windows服务程序和安装程序制作图解 及 VS 2010创建、安装、调试 windows服务(windows service)

    .net Windows服务程序和安装程序制作 最近项目中用到window服务程序,以前没接触过,比较陌生,花了两天的时间学习了下,写了个简单的服务,但在制作安装程序的时候,参照网上很多资料,却都制作 ...

  5. VS创建、安装、调试 windows服务(windows service)

    1.创建 windows服务 项目   文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服 ...

  6. C# VS 2010创建、安装、调试 windows服务(windows service)

    在一个应用程序中创建多个 windows 服务的方法和 1083 的解决办法 错误解决方案 ------------------------------------------------------ ...

  7. VS 2010一步步开发windows服务(windows service)

    基于0起步来创建一个服务,做到简单的记录时间日志功能,其具体招行方法可自行添加. 1.创建服务 2.删除默认服务文件 3.添加自己的服务文件 4.更改启动项目 5. 引用 using System.T ...

  8. 通过cmd 使用 InstallUtil.exe 命令 操作 windows服务 Windows Service

    要安装windows service 首先要找到 InstallUtil.exe,InstallUtil.exe位置在 C:\Windows\Microsoft.NET\Framework\v4.0. ...

  9. 玩转Windows服务系列——创建Windows服务

    创建Windows服务的项目 新建项目->C++语言->ATL->ATL项目->服务(EXE) 这样就创建了一个Windows服务项目. 生成的解决方案包含两个项目:Servi ...

随机推荐

  1. Transient的作用

    1:transient的作用及其使用方法 当一个对象实现类Serilizable接口,那么这个类就可以被序列化,java的这种序列化的模式为开发者提供了很多的便利. 然而在实际开发中,我们常常遇到这样 ...

  2. EL表达式杂项

    1.<%@ page isELIgnored="false" %> 是否忽略EL表达式,如果值为ture,那么  ${..}这样的会直接原样输出,不会进行EL表达式计算 ...

  3. Stream流

    在Node中,存在各式各样不同的数据流,Stream(流)是一个由不同对象实现的抽象接口.例如请求HTTP服务器的request是一个 流,类似于stdout(标准输出):包括文件系统.HTTP 请求 ...

  4. 机器学习之sklearn——SVM

    sklearn包对于SVM可输出支持向量,以及其系数和数目: print '支持向量的数目: ', clf.n_support_ print '支持向量的系数: ', clf.dual_coef_ p ...

  5. [LeetCode] Binary Watch 二进制表

    A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom ...

  6. [LeetCode] Contains Duplicate III 包含重复值之三

    Given an array of integers, find out whether there are two distinct indices i and j in the array suc ...

  7. [LeetCode] Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  8. JS组件系列——BootstrapTable 行内编辑解决方案:x-editable

    前言:之前介绍bootstrapTable组件的时候有提到它的行内编辑功能,只不过为了展示功能,将此一笔带过了,罪过罪过!最近项目里面还是打算将行内编辑用起来,于是再次研究了下x-editable组件 ...

  9. C#中的WebBrowser控件的使用

    0.常用方法   Navigate(string urlString):浏览urlString表示的网址 Navigate(System.Uri url):浏览url表示的网址 Navigate(st ...

  10. Mysql字符串字段判断是否包含某个字符串的3种方法

    方法一: SELECT * FROM users WHERE emails like "%b@email.com%"; 方法二: 利用MySQL 字符串函数 find_in_set ...