When we need a program to run for a long time, but do not need to display the interface can consider using Windows service to implement. This blog will briefly explain how to create a Windows service, install/Uninstall Windows service.
To create a new Windows Service project:
Delete the auto-generated Service1.cs file, create a new Windowsservice class, and inherit the ServiceBase.
Class Windowsservice:servicebase {public Windowsservice ()} {this. ServiceName = "Test Windows Service"; This. EventLog.Log = "Application"; This. Canhandlepowerevent = true; This. Canhandlesessionchangeevent = true; This. CanPauseAndContinue = true; This. CanShutdown = true; This. CanStop = true; } #region//can place the requirement implementation code within the overridden method protected override void Dispose (bool disposing) {BA Se. Dispose (disposing); } protected override void OnStart (string[] args) {base. OnStart (args); } protected override void OnStop () {base. OnStop (); } protected override void OnPause () {base. OnPause (); } protected override void OnContinue () {base. OnContinue (); } protected override void OnShutdown () {base. OnShutdown (); } protected override void Oncustomcommand (int command) {base. Oncustomcommand (command); } protected override bool Onpowerevent (PowerBroadcastStatus powerstatus) {return base. Onpowerevent (Powerstatus); } protected override void Onsessionchange (SessionChangeDescription changedescription) {base. Onsessionchange (changedescription); } #endregion}
Create a new Windowsserviceinstaller class, add a System.Configuration.Install reference,
[Runinstaller (True)] Class Windowsserviceinstaller:installer {public Windowsserviceinstaller () { ServiceProcessInstaller ServiceProcessInstaller = new ServiceProcessInstaller (); ServiceInstaller ServiceInstaller = new ServiceInstaller (); Serviceprocessinstaller.account = Serviceaccount.localsystem; Serviceprocessinstaller.username = null; Serviceprocessinstaller.password = null; Serviceinstaller.displayname = "CSharp Windows Service"; Serviceinstaller.starttype = servicestartmode.automatic; Serviceinstaller.servicename = "Windows Service"; This. Installers.add (ServiceProcessInstaller); This. Installers.add (ServiceInstaller); } }
Compile the project, at which point the compiled CSWindowsService.exe runs after the prompt:
We need to deploy Windows Service through Installutil.exe.
Run developer Command Prompt as Administrator. deployment Command: installutil/i file path .
Example: installutil/i D:\CSWindowsService.exe
Uninstall the command installutil/u file path.
Here, a simple Windows serive is finished.
For more information about Windows service, please refer to the MSDN documentation.
Thank you for reading, code click here to download.
C # Create a Windows Service