/// <summary> ///Service Invocation Control/// </summary> Public classWinservicecontroller {/// <summary> ///Service start enabled/// </summary> /// <typeparam name= "T" >types of service calls</typeparam> /// <param name= "ServiceName" >name of the service</param> /// <param name= "args" >application launches passed in Parameters</param> Public Static voidState<t> (stringServiceName,string[] args)whereT:servicebase, Iservicecontroller,New() { stringKey0 =AppDomain.CurrentDomain.FriendlyName; if(args. Length >0) { stringstr = args[0]. ToLower (); Try { if(str = ="-install"|| str = ="- I.") { #region //Install the service if(NULL==serviceisexisted (ServiceName)) {//if it is not installed, install stringKey = AppDomain.CurrentDomain.BaseDirectory +Key0; Managedinstallerclass.installhelper (New string[] {key}); ServiceController C=NewServiceController (Key0. Substring (0, Key0. Length-4)); C.start (); } Else{log.write ("The service is already installed! No more installation! "); } #endregion } Else if(str = ="-uninstall"|| str = ="- u") { #region //Uninstall the serviceServiceController SC=serviceisexisted (ServiceName); if(NULL!=SC) {//if it is already installed, uninstall the service if(SC. Status! =servicecontrollerstatus.stopped) {sc. Stop ();//Stop ServiceSc. WaitForStatus (servicecontrollerstatus.stopped);//waiting for the service to stop completely; really handy function ~ } stringKey = AppDomain.CurrentDomain.BaseDirectory +AppDomain.CurrentDomain.FriendlyName; Managedinstallerclass.installhelper (New string[] {"/ u", key}); } Else{log.write ("The service is not installed! You cannot uninstall a service that does not exist! "); } #endregion } Else if(str = ="-start"|| str = ="- S") { #region //run the service directly as an applicationLog.write ("Message service startup started"); T MSM=NULL; Try{MSM=NewT (); Msm. Start (); } Catch(Exception msg) {if(NULL!=MSM) {MSM. Stop (); } } #endregion } } Catch(Exception msg) {log.write (msg. Message+Msg. StackTrace); Log.write ("Message Service exception ended"); } } Else { #region //Start the service Try{Servicebase.run (NewT ()); } Catch(Exception msg) {log.write (msg. Message+Msg. StackTrace); Log.write ("Message Service exception ended"); } #endregion } } /// <summary> ///checks whether the specified service exists. /// </summary> /// <param name= "ServiceName" >Service name to look for</param> /// <returns>returns True if it exists</returns> Private StaticServiceController serviceisexisted (stringsvcname) {servicecontroller[] Services=servicecontroller.getservices (); foreach(ServiceController sinchservices) { if(S.servicename = =svcname) { returns; } } return NULL; } }
View Code
Call:
Program files in the Windows service application
Static Class Program
{
<summary>
The main entry point for the application.
</summary>
public static void Main (string[] args)
{
Winservicecontroller.state<service1> ("Windows Service Application exe name", args);
}
}
Windows Service Control classes