1. Create a WINDOWS Service Program Project WinSrv_A in VS. NET2003.
2. Change the SERVICENAME attribute of SERVICE1.CS to the name of the service you want to create. In Service Manager> name, you can see your service name.
3. Press F7 to enter the code window. There are two overload functions in it: // protected override void OnStart (string [] args)
// {...} // This function is executed after you start the service.
// Protected override void OnStop ()
// {...} // This function is executed after you stop the service.
Here is a simple function to record the start time and end time of the service.
Write a log file.
Protected override void OnStart (string [] args)
{
// TODO: Add code here to start the service.
String s = System. DateTime. Now. ToString ();
If (! File. Exists ("c: srvlog.txt "))
{
StreamWriter sr = File. CreateText ("c: bbirdlog.txt ");
Sr. WriteLine ("------------------------- STARTSRV ---------------------");
Sr. WriteLine ("My new service starts at {0}", s );
Sr. WriteLine ("I can write INTEGER {0} or floating point {1}, etc..", 1, 4.2 );
Sr. Close ();
}
Else
{
StreamWriter sr = File. AppendText ("c: bbirdlog.txt ");
Sr. WriteLine ("------------------------- STARTSRV ---------------------");
Sr. WriteLine ("My new service starts at {0}", s );
Sr. WriteLine ("I can write INTEGER {0} or floating point {1}, etc..", 1, 4.2 );
Sr. Close ();
}
}
/// <Summary>
/// Stop this service
/// </Summary>
Protected override void
OnStop ()
{
// TODO: Add code here to stop the service.
String s1 = System. DateTime. Now. ToString ();
If (! File. Exists ("c: srvlog.txt "))
{
StreamWriter sr = File. CreateText ("c: bbirdlog.txt ");
Sr. WriteLine ("--------------------------- STOPSRV ---------------------");
Sr. WriteLine ("My new service stops at {0}", s1 );
Sr. Close ();
}
Else
{
StreamWriter sr = File. AppendText ("c: bbirdlog.txt ");
Sr. WriteLine ("--------------------------- STOPSRV ---------------------");
Sr. WriteLine ("My new service stops at {0}", s1 );
Sr. Close ();
}
}
4. Return to the design window, right-click and choose add installer to generate serviceInstaller1 and
ServiceProcessInstaller1 TWO COMPONENTS
Rewrite the ServiceName attribute of serviceInstaller1 to your service program name, and set the Startup Mode
Set to AUTOMATIC
Rewrite the attribute account of serviceProcessInstaller1
LocalSystem
5. Compile the link to generate a service program.
6. Use the. net framework tool INSTALLUTIL to install the service program.