Create a Windows service in C # (Windows services)
Learn:
First step: Create a service framework
Create a new Windows Service project, select the Windows Services (Windows Service) option from the Visual C # project, and give the project a new file name
, then click OK. Now there is a Service1.cs class in the project:
The implications of viewing each of its properties are:
Autolog whether to automatically write to the system's log files
Canhandlepowerevent receive power events during service
Whether the CanPauseAndContinue service accepts requests that are paused or continue to run
Whether the CanShutdown service receives a notification when the computer on which it is running is closed so that the OnShutdown procedure can be called
Whether the CanStop service accepts a request to stop running
ServiceName Service Name
Step Two: Add functionality to your service
As we can see in the. cs code file, there are two ignored functions OnStart and OnStop.
The OnStart function executes when the service is started, and the OnStop function executes when the service is stopped. This example is: When starting and stopping the service, the timer displays "Hello, hello";
, first drag a Timer control in the Service1.cs design, set its interval=60000, and the function to do
The code is as follows:
The OnStart function executes when the service is started
protected override void OnStart (string[] args)
{
This.timer1.Start ();
}
The OnStop function executes when the service is stopped
protected override void OnStop ()
{
This.timer1.Stop ();
}
private void Timer1_Tick (object sender, EventArgs e)
{
System.Diagnostics.Process.Start ("http://www.baidu.com");
}
Step three: Add the installer to the service application
The steps to add the installer to the service application are:
1: In the solution, right-click the service Service1.cs Design view.
2: In the Properties window, click-Add the Installer
A new class ProjectInstaller and two installation components ServiceProcessInstaller and ServiceInstaller are added to the project, and the service
The value of the property is copied to the component.
3: To determine how to start the service, click the ServiceInstaller component and set the StartType property to the appropriate value.
After the Manual service is installed, it must be started manually.
Automatic the service will start automatically every time the computer restarts.
The Disabled service could not be started.
4: Change the Account property of the ServiceProcessInstaller class to LocalSystem
This way, the service will always start, regardless of which user is logged on to the system.
Fourth step: Build the Service Program
Build the project Shift+f6 by selecting Build from the Build menu. Or rebuild the project note do not run the project by pressing the F5 key-the service project cannot be run in this manner.
Fifth step: Installation and uninstallation of the service
Access the directory where the compiled executable file is located in the project.
Run InstallUtil.exe from the command line with the output of the project as a parameter. Enter the following code on the command line:
InstallUtil WindowsService1.exe
Uninstall Service
Run InstallUtil.exe from the command line with the output of the project as a parameter.
Installutil/u WindowsService1.exe
Attached: Installutil.exe in installing vs computer's C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
To the VS2008 command prompt Installutil.exe/? can view its help description
Recommended method for installing a service in another
Use WinForm to invoke the installation, when the button is clicked, the service is installed.
1. Project needs to add references System.Configuration.Install and system.serviceprocess
The code is as follows:
Using System.Configuration.Install;
Using System.ServiceProcess;
<summary>
Installation Services
</summary>
private void Btninstall_click (object sender, EventArgs e)
{
string[] args = {"WindowsService1.exe"};
Uninstall Service string[] args = {"/u", "WindowsService1.exe"};
if (! Serviceisexisted ("Service1"))//The Service1 here is the name of the service that corresponds to the real project
{
Try
{
Managedinstallerclass.installhelper (args); Parameter args is when you install with the InstallUtil.exe tool
Parameters. is usually a filename of exe
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
Return
}
}
Else
{
MessageBox.Show ("The service already exists and does not have to be installed repeatedly.") ");
}
}
<summary>
Checks whether the specified service exists.
</summary>
<param name= "ServiceName" > Name of service to find </param>
<returns></returns>
private bool Serviceisexisted (string svcname)
{
servicecontroller[] Services = servicecontroller.getservices ();
foreach (ServiceController s in services)
{
if (S.servicename = = svcname)
{
return true;
}
}
return false;
}
Manual installation is possible through the static method Installhelper in the System.Configuration.Install.ManagedInstallerClass class. of this method
The signature is as follows:
public static void Installhelper (string[] args)
The parameter args is the parameter you use when installing with the InstallUtil.exe tool. is usually a filename of exe
Sixth Step: Commissioning Service
After installation, the service does not start automatically and the service cannot interact with the desktop
1. Set the service to start automatically after installation
Add Afterinstall event for ServiceInstaller1
Using System.Diagnostics;
private void Serviceinstaller1_afterinstall (object sender, Installeventargs e)
{
System.ServiceProcess.ServiceController s = new System.ServiceProcess.ServiceController ("Service1");
S.start ();//Set up service to start immediately after installation
}
2. Set the Allow service to interact with desktop method
To have the service start an application, modify the properties of the service, tick allow service to interact with the desktop,
#region setting up services to interact with the desktop
<summary>
Set the service to interact with the desktop and use it in the ServiceInstaller1 Afterinstall event
</summary>
<param name= "ServiceName" > Service name </param>
private void Setservicedesktopinsteract (string serviceName)
{
System.Management.ManagementObject wmiservice = new System.Management.ManagementObject (string. Format
("Win32_service.name= ' {0} '", ServiceName));
System.Management.ManagementBaseObject Changemethod = wmiservice.getmethodparameters ("change");
changemethod["DesktopInteract"] = true;
System.Management.ManagementBaseObject Utparam = Wmiservice.invokemethod ("Change", Changemethod,
NULL);
}
#endregion
3.windows service is not executing the Timer control, the workaround
Remove the timer control used above
Public Service1 ()
{
InitializeComponent ();
System.Timers.Timer t = new System.Timers.Timer ();
T.interval =1000*15;
t.elapsed + = new System.Timers.ElapsedEventHandler (runwork);
T.autoreset = true;//Whether the setting is executed once (false) or always executed (true);
t.enabled = true;//is executed
}
public void Runwork (object source, System.Timers.ElapsedEventArgs e)
{
Things to handle on a regular basis
So the service can perform the task on a regular basis.
}
Summary: Windows services Programming
1. The service does not execute the Timer control
2. After the default service installation is complete, it is not started automatically and cannot interact with the desktop
3. When installing the service, it is recommended to create a new WinForm project to perform the installation and uninstallation of the service with the WinForm project.
The 4.OnStart function executes when the service is started, and the OnStop function executes when the service is stopped.
5. Right-click-Add service to Application
Transferred from: http://blog.itpub.net/23109131/viewspace-688117/
Create a Windows service in C # (Windows services)