1. Create a C # project
Create an EXE project in WinForm or command line format. Add references to System. ServiceProcess. dll and System. Configuration. Install. dll.
2. Create a service class
Add a class that inherits the System. ServiceProcess. ServiceBase type and sets the ServiceName attribute in the constructor to specify the service name. Then, reload its OnStart method to respond to the Service Startup event, reload the OnStop method to respond to the Service stop event, and reload the OnPause method to respond to the service suspension event, reload the OnContinue method to respond to events that restore services.
When you reload these methods, you must return them immediately. There cannot be long-term operations. If the processing time is too long, the Windows Service Manager will feel that the Windows Service has stopped responding and reports an error. Therefore, we can use a thread for actual work, while the OnStart method creates a thread, the OnStop method closes the thread, the OnPause method suspends the thread, and the OnContinue method restores the running thread.
3. Start the service
In the main function, call "System. ServiceProcess. ServiceBase. Run (instance of the Custom Service class)" to Run the service. For example, "System. ServiceProcess. ServiceBase. Run (new MyService ()", here MyService is inherited from ServiceBase.
Note: You can create a "Windows Service" project in VS2005. The code is automatically generated by the development environment.
Bytes -------------------------------------------------------------------------------------------------------------
4. Create a service installation class
Add a new class that inherits from the System. Configuration. Install. Installer type. This type is used in combination with the installation command line tool installutil.exe in the Microsoft. NET Frame. We add the System. ComponentModel. RunInstallerAttribute feature for this type,
[RunInstaller (true)]
Public partial class ServiceInstaller: Installer
{
Public ServiceInstaller ()
{
InitializeComponent ();
}
}
The System. ServiceProcess. ServiceInstaller object and System. ServiceProcess. ServiceProcessInstaller object are used in its constructor to provide the System with the installation information of the service.
Code Partial class ServiceInstaller
{
/// <Summary>
/// Required designer variables.
/// </Summary>
Private System. ComponentModel. IContainer components = null;
/// <Summary>
/// Clear all resources in use.
/// </Summary>
/// <Param name = "disposing"> If the managed resource should be released, the value is true; otherwise, the value is false. </Param>
Protected override void Dispose (bool disposing)
{
If (disposing & (components! = Null ))
{
Components. Dispose ();
}
Base. Dispose (disposing );
}
# Code generated by the region component designer
/// <Summary>
///