This article describes a simple Windows Service implemented in C.
The function is to add a log in the event log of windows when the service is started and stopped.
After a Windows Service Project is created in Visual Studio 2008, A service1 service is automatically generated. Its name is service1 by default. I will first change its file name from service1.cs to itstestservice. CS, and then in itstestservice. change the service name to itstestservice In the attribute of the CS designer view. Otherwise, the following error will be reported when the service is started after the service is added:
The ITS Test Service failed to start due to the following error:
Configure to executeProgramThis service cannot be executed.
Install services
SC create itstestservice binpath ="Path to service EXE"Type = share start = auto displayname ="Its Test Service"
Uninstall Service
SC Delete itstestservice
Because the service installation name is service1.
Code
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 {
15Initializecomponent ();
16}
17
18 Protected Override Void Onstart ( String [] ARGs)
19 {
20Writelog ("Itstestservice started.");
21}
22
23 Protected Override Void Onstop ()
24 {
25Writelog ("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 {
37EventLog. createeventsource (source, log );
38}
39
40 EventLog. writeentry (source, eventstring );
41 }
42 }
43 }
Source code: Download