Installer1.cs
Code
1 using system;
2 using system. Collections. Generic;
3 using system. componentmodel;
4 using system. configuration. Install;
5 using system. serviceprocess;
6
7 namespace windowsservice1
8 {
9 [runinstaller (true)]
10 public partial class installer1: Installer
11 {
12 private serviceinstaller;
13 private serviceprocessinstaller processinstaller;
14
15 public installer1 ()
16 {
17 initializecomponent ();
18 serviceinstaller = new serviceinstaller ();
19 processinstaller = new serviceprocessinstaller ();
20
21 // set the running mode after installation
22 processinstaller. Account = serviceaccount. LocalSystem;
23
24 // if you need to use another user to simulate the operation, you need to change it to serviceaccount. User
25 // processinstaller. Username = "Administrator ";
26 // processinstaller. Password = "abcdefg ";
27
28 serviceinstaller. servicename = "snowfoxservice ";
29 serviceinstaller. Description = "snowfox test Windows Service ";
30
31 serviceinstaller. afterinstall + = new installeventhandler (serviceinstaller_afterinstall );
32 serviceinstaller. beforeuninstall + = new installeventhandler (serviceinstaller_beforeuninstall );
33
34 // install the two services in the package
35 installers. Add (serviceinstaller );
36 installers. Add (processinstaller );
37 // close the ticket
38}
39
40 void serviceinstaller_beforeuninstall (Object sender, installeventargs E)
41 {
42 // The purpose here is to suspend the service when the service needs to be uninstalled.
43 servicecontroller con = new servicecontroller ("snowfoxservice ");
44 try
45 {
46 If (con. status! = Servicecontrollerstatus. Stopped)
47 {
48 con. Stop ();
49}
50}
51 catch
52 {
53}
54
55
56 // throw new exception ("the method or operation is not implemented .");
57}
58
59 void serviceinstaller_afterinstall (Object sender, installeventargs E)
60 {
61 // The purpose here is to start the service after the service is installed. Therefore, you must first obtain the service object and then start
62 servicecontroller con = new servicecontroller (serviceinstaller. servicename );
63 con. Start ();
64 // throw new exception ("the method or operation is not implemented .");
65}
66}
67}
Services1.cs
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 windowsservice1
10 {
11 public partial class service1: servicebase
12 {
13 public service1 ()
14 {
15 initializecomponent ();
16}
17
18 protected override void onstart (string [] ARGs)
19 {
20 // todo: Add code here to start the service.
21 This. EventLog. writeentry ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", eventlogentrytype. information );
22}
23
24 protected override void onstop ()
25 {
26 // todo: Add code here to stop the service.
27
28
29}
30}
31}
32