Transferred from: http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html
Recently due to work needs, wrote some Windows service programs, have some experience, I now summarize write out.
Currently I know that there are 3 ways to create a Windows service:
A. Leveraging the. NET Framework class ServiceBase
B. Using Component Topshelf
C. Using gadgets instsrv and Srvany
Below I use these 3 ways, respectively, to do a Windows service program, the program function is every 5 seconds to the program directory logging:
A. Leveraging the. NET Framework class ServiceBase
Features of the method: simple, good compatibility
implemented by inheriting the. NET Framework class ServiceBase
1th Step: Create a new Windows service
Public partial class Service1:servicebase {readonly Timer _timer; private static readonly String FileName = Path.getdirectoryname (assembly.getexecutingassembly (). Location) + @ "\" + "test.txt"; Public Service1 () {InitializeComponent (); _timer = new Timer {AutoReset = true, Enabled = true}; _timer. Elapsed + = Delegate (object sender, Elapsedeventargs e) {this.witre (string. Format ("Run DateTime {0}", DateTime.Now)); }; } protected override void OnStart (string [] args) {this.witre (string. Format ("Start DateTime {0}", DateTime.Now)); } protected override void OnStop () {this.witre (string. Format ("Stop DateTime {0}", DateTime.Now) + Environment.NewLine); } void Witre (String context) {STReamwriter SW = File.appendtext (FileName); Sw. WriteLine (context); Sw. Flush (); Sw. Close (); } }
2nd Step: Add Installer
[Runinstaller (True)] public partial class Installer1:System.Configuration.Install.Installer { private ServiceInstaller ServiceInstaller; Private ServiceProcessInstaller Processinstaller; Public Installer1 () { InitializeComponent (); Processinstaller = new ServiceProcessInstaller (); ServiceInstaller = new ServiceInstaller (); Processinstaller.account = Serviceaccount.localsystem; Serviceinstaller.starttype = servicestartmode.automatic; Serviceinstaller.servicename = "My_windowsservice"; Serviceinstaller.description = "Windowsservice_description"; Serviceinstaller.displayname = "Windowsservice_displayname"; Installers.add (ServiceInstaller); Installers.add (Processinstaller); } }
3rd Step: Install, uninstall
CMD command
InstallUtil Windowsservice_test.exe (installing Windows Services)
installutil/u windowsservice_test.exe (uninstall Windows service)
Code Download: Http://files.cnblogs.com/aierong/WindowsService_test.rar
B. Using Component Topshelf
This approach features: code simple, open source components, Windows services can run multiple instances
Topshelf is an open-source, cross-platform service framework that supports Windows and mono, and allows you to build a service that is easy to use with just a few lines of code. Official website: http://topshelf-project.com
1th step: Referencing Assemblies TopShelf.dll and Log4net.dll
2nd step: Create a service class MyClass, which contains two methods start and stop, also includes a timer timer, every 5 seconds to the text file to write characters
public class MyClass {readonly Timer _timer; private static readonly String FileName = directory.getcurrentdirectory () + @ "\" + "test.txt"; Public MyClass () {_timer = new timer () {AutoReset = True, Enabled = true}; _timer. Elapsed + = Delegate (object sender, Elapsedeventargs e) {this.witre (string. Format ("Run DateTime {0}", DateTime.Now)); }; } void Witre (String context) {StreamWriter SW = File.appendtext (FileName); Sw. WriteLine (context); Sw. Flush (); Sw. Close (); } public void Start () {this.witre (string. Format ("Start DateTime {0}", DateTime.Now)); } public void Stop () {this.witre (string. Format ("Stop DateTime {0}", DateTime.Now) + Environment.NewLine);} }
3rd Step: Use Topshelf to host our service, mainly topshelf how to set up our service configuration and method call when start and stop
Class program { static void Main (string [] args) { Hostfactory.run (x = = { x.service<my Class> ((s) = { s.setservicename ("Ser"); S.constructusing (name = new MyClass ()); S.whenstarted ((t) = T.start ()); S.whenstopped ((t) = T.stop ()); ); X.runaslocalsystem (); Description of the service x.setdescription ("topshelf_description"); The display name of the service x.setdisplayname ("Topshelf_displayname"); Service name x.setservicename ("Topshelf_servicename");} ); }
4th Step: cmd command
Consoleapp_topshelf.exe Install (installing Windows Services)
Consoleapp_topshelf.exe Uninstall (uninstall Windows service)
Code Download: Http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar
C. Using gadgets instsrv and Srvany
This method features: Code super simple, WindowsForm program can, and support program interaction (I like the characteristics), as if not support Win7, support XP Win2003
2 gadgets are introduced first:
Instsrv.exe: Used to install and uninstall executable services
Srvany.exe: Used to run any EXE program as a Windows service
These 2 tools are a practical gadget for the Microsoft Windows Resource Kits Toolset
You can get http://www.microsoft.com/en-us/download/details.aspx?id=17657 by downloading and installing Microsoft Windows Resource Kits
1th Step: New WindowsForm Program
Public partial class Form1:form {Timer _timer; private static readonly String FileName = Application.startuppath + @ "\" + "test.txt"; Public Form1 () {InitializeComponent (); } private void Form1_Load (object sender, EventArgs e) {_timer = new timer () { Enabled = true, Interval = 5000}; _timer. Tick + = Delegate (object _sender, EventArgs _e) {this.witre (string. Format ("Run DateTime {0}", DateTime.Now)); }; } void _timer_tick (object sender, EventArgs e) {throw new NotImplementedException (); } void Witre (String context) {StreamWriter SW = File.appendtext (FileName); Sw. WriteLine (context); Sw. Flush (); Sw. Close (); } private void Button1_Click (object sender, evenTargs e) {MessageBox.Show ("Hello"); } }
2nd step: Install, uninstall
The installation step of the service is 5 small steps:
(1) Open cmd, enter the following, where Windowsforms_windowsservice is the name of the service you want to create
Format: Directory absolute path \instsrv windowsforms_windowsservice Directory absolute path \srvany.exe
For example:
D:\TempWork\win\Debug\instsrv.exe Windowsforms_windowsservice D:\TempWork\win\Debug\srvany.exe
(2) Regedit open the Registry Editor and locate the following directory
Hkey_local_machine\system\currentcontrolset\services\windowsforms_windowsservice
(3) Right-click Windowsforms_windowsservice, create an "item" with the name "Parameters"
(4) left mouse button click "Parameters", right click on the right mouse button, create a "string value" (REG_SZ), the name is "Application", the value data fill in the directory executable file absolute path + file name
For example:
D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe
(5) Open Services.msc Service Control Panel, find Windowsforms_windowsservice service, right mouse button-Properties-login, tick "Allow service to interact with desktop"
Start the service, you can see the program interface
Uninstall Service
D:\TempWork\win\Debug\instsrv.exe Windowsforms_windowsservice REMOVE
Code Download: Http://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar
(go) Create a Windows service (Windows Services) Summary of n ways