Go C # Create a Windows service

Source: Internet
Author: User

Original address: http://blog.itpub.net/23109131/viewspace-688117/

First step: Create a service framework

To create a new Windows Service project, you can select the Windows Services (Windows Service) option from the Visual C # project, give the project a new file name, and 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 time to display "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:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 //OnStart函数在启动服务时执行  protected override void OnStart(string[] args)  {      this.timer1.Start();  } // OnStop函数在停止服务时执行  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

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's property values are 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

?
1 2 3 4 5 6 using system.diagnostics; private void serviceinstaller1_afterinstall ( object Code class= "CSharp Plain" >sender, Installeventargs e) { &NBSP;&NBSP;&NBSP;&NBSP; system.serviceprocess.servicecontroller s = new System.ServiceProcess.ServiceController ( "Service1" &NBSP;&NBSP;&NBSP;&NBSP; s.start (); //set up service to start immediately after installation

2. Set the Allow service to interact with desktop method

To have the service launch an application, modify the properties of the service, tick allow service to interact with the desktop, #region set up the service to interact with the desktop

?
1 2 3 4 5 6 7 8 9 10 11 12 /// <summary> /// 设置服务与桌面交互,在serviceInstaller1的AfterInstall事件中使用 /// </summary> /// <param name="serviceName">服务名称</param> private void SetServiceDesktopInsteract(string serviceName) {  System.Management.ManagementObject wmiService = newSystem.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<br>);   }<br>#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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.