创建Windows服务

  在OnStart和OnStop方法中添加服务启动和停止时的处理代码

        protected override void OnStart(string[] args)
{
}

protected override void OnStop()
{
}

  还需要添加Installer才能加载服务,在Service类的设计界面 右键-> Add Installer。 在Installer类中,serviceInstaller属性:ServiceName,StartType;设置serviceProcessInstaller的Account为LocalSystem。

  Service类例子,记录远程登录用户事件,在Service类中添加如下代码:

  需要添加 System.ServiceProcess 引用。

  (需要设置Service属性 CanHandleSessionChangeEvent 为true)

 1 protected override void OnSessionChange(SessionChangeDescription changeDescription)
2 {
3 string file = @"C:\log.txt";
4 string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
5 switch (changeDescription.Reason)
6 {
7 case SessionChangeReason.RemoteConnect:
8 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "RemoteConnect"));
9 break;
10 case SessionChangeReason.RemoteDisconnect:
11 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "RemoteDisconnect"));
12 break;
13 case SessionChangeReason.SessionLogoff:
14 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "SessionLogoff"));
15 break;
16 case SessionChangeReason.SessionLogon:
17 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "SessionLogon"));
18 break;
19 case SessionChangeReason.SessionRemoteControl:
20 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "SessionRemoteControl"));
21 break;
22 case SessionChangeReason.SessionUnlock:
23 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "SessionUnlock"));
24 break;
25 case SessionChangeReason.SessionLock:
26 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "SessionLock"));
27 break;
28 case SessionChangeReason.ConsoleConnect:
29 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "ConsoleConnect"));
30 break;
31 case SessionChangeReason.ConsoleDisconnect:
32 File.AppendAllText(file, string.Format("{0}\r\n{1}\r\n\r\n", now, "ConsoleDisconnect"));
33 break;
34 }
35 }

  加载服务:installutil xxx.exe

  卸载服务:installutil /u xxx.exe  或  sc delete ServiceName

  使用C#代码实现服务管理, windows service 管理类如下:

  1     public class WindowsServiceHelper
2 {
3 /// <summary>
4 /// Check whether the windows service exists.
5 /// </summary>
6 /// <param name="service">service name</param>
7 /// <returns></returns>
8 public static bool ServiceIsExisted(string service)
9 {
10 ServiceController[] services = ServiceController.GetServices();
11
12 foreach (ServiceController srv in services)
13 {
14 if (string.Compare(service, srv.ServiceName, true) == 0)
15 {
16 return true;
17 }
18 }
19 return false;
20 }
21
22 /// <summary>
23 /// Get the status of the windows service.
24 /// </summary>
25 /// <param name="service">name of the windows service</param>
26 /// <returns>status of the windows service</returns>
27 public static ServiceControllerStatus GetStatus(string service)
28 {
29 ServiceController[] services = ServiceController.GetServices();
30
31 foreach (ServiceController srv in services)
32 {
33 if (string.Compare(service, srv.ServiceName, true) == 0)
34 {
35 return srv.Status ;
36 }
37 }
38
39 throw new Exception(string.Format("There is not the service({0}).", service));
40 }
41
42 /// <summary>
43 /// Install windows service with install file.
44 /// </summary>
45 /// <param name="installFile">intalling file(*.exe)</param>
46 public static void InstallService(string installFile)
47 {
48 string serviceName = installFile.Replace(".exe", "");
49
50 if (!ServiceIsExisted(serviceName))
51 {
52 try
53 {
54 ManagedInstallerClass.InstallHelper(new string[] { installFile });
55 }
56 catch (Exception ex)
57 {
58 throw ex;
59 }
60 }
61 else
62 {
63 throw new Exception(string.Format("The {0} has beed existed.", serviceName));
64 }
65 }
66
67 /// <summary>
68 /// Start windows service
69 /// </summary>
70 /// <param name="service">the name of the windows service</param>
71 public static void ServiceStart(string service)
72 {
73 ServiceController[] services = ServiceController.GetServices();
74
75 foreach (ServiceController s in services)
76 {
77 if (s.ServiceName == service)
78 {
79 if (s.Status == ServiceControllerStatus.Stopped)
80 {
81 try
82 {
83 s.Start();
84 }
85 catch (Exception ex)
86 {
87 throw ex;
88 }
89 }
90 else
91 {
92 throw new Exception(string.Format("{0} is {1}, failed to start...", service, s.Status.ToString()));
93 }
94 }
95 }
96 }
97
98 /// <summary>
99 /// Stop windows service
100 /// </summary>
101 /// <param name="service">the name of the windows service</param>
102 public static void ServiceStop(string service)
103 {
104 ServiceController[] services = ServiceController.GetServices();
105
106 foreach (ServiceController s in services)
107 {
108 if (s.ServiceName == service)
109 {
110 if (s.Status == ServiceControllerStatus.Running)
111 {
112 try
113 {
114 s.Stop();
115 }
116 catch (Exception ex)
117 {
118 throw ex;
119 }
120 }
121 else
122 {
123 throw new Exception(string.Format("{0} is {1}, failed to stop...", service, s.Status.ToString()));
124 }
125 }
126 }
127 }
128 }

转载于:https://www.cnblogs.com/Peter-Zhang/articles/2116688.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值