Run Visual Studio. NET to create a C # Windows Service Project
Project name: testservice
Code :
Using System;
Using System. Collections. Generic;
Using System. componentmodel;
Using System. Data;
Using System. diagnostics;
Using System. serviceprocess;
Using System. text;
Using System. Threading;
Using System. Windows. forms;
Namespace Testservice
{
Partial Class Careeye: servicebase
{
Private Thread mainthread;
Public Careeye ()
{
Initializecomponent ();
// Todo: add any initialization after the initcomponent call
Mainthread = New Thread ( New Threadstart (threadfunc ));
Mainthread. Priority = Threadpriority. Lowest;
}
Protected Override Void Onstart ( String [] ARGs)
{
//Todo: Add code here to start the service.
Mainthread. Start ();
}
Protected Override Void Onstop ()
{
//Todo: Add code here to stop the service.
Mainthread. Abort ();
}
Public Static Void Threadfunc ()
{
Int Lasthour = Datetime. Now. hour;
While ( True )
{
System. Threading. thread. Sleep (6 0000 );
If (Datetime. Now. Hour - 1 = Lasthour)
{
MessageBox. Show ( " To take good care of your eyes, please take a 5-minute break and look into the distance! " , " Warning " , Messageboxbuttons. OK, messageboxicon. Warning, messageboxdefaultbutton. button1, messageboxoptions. defaultdesktoponly );
Lasthour = Datetime. Now. hour;
}
}
}
}
}
Add Service Installation Program
It is not enough to create a Windows Service and only use the installutil program to install the service. You must add a service installer to your Windows Service so that installutil or any other installer can know how your service is configured.
1. Switch the service program to the design view.
2. Right-click the design view and select "add installer"
3. Switch to the design view of the newly added projectinstaller.
4. Set the attributes of the serviceinstaller1 component:
1) servicename = My Sample Service
2) starttype = automatic
5. Set the attributes of the serviceprocessinstaller1 component
1) account = LocalSystem
6. Generate a solution
After completing the preceding steps, Visual Studio automatically generates the following Source code , Which is included in the source file projectinstaller. CS.
Install Windows Services:
Install a service. Go to cmd Image To access the framework2.0 file, for example:
Cd c: Windows Microsoft. netframeworkv2.0.50727
After hitting
Installutil F: w2.exe. the uninstallation service is installutil F: w2.exe-U.
Now you have to start the service,
Start the installed Service in windows.