C # create a window service

Source: Internet
Author: User

Using System;
Using System. Threading;
Using System. ServiceProcess;
Using System. Collections;
Using System. Configuration. Install;
Using System. Diagnostics;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. Collections. Specialized;
Using System. IO;
Namespace WSGPSServices
{
Public partial class myService: ServiceBase
{
# Region member variables
Public string strCurrPath = new System. IO. FileInfo (System. Reflection. Assembly. GetExecutingAssembly (). Location). Directory. FullName;
Public string servicesname = "WSGPSServices"; // Service
Public string Proceename = "WSGPSGateway.exe"; // Process
# Endregion
Protected override void Dispose (bool disposeing)
{
If (disposeing)
{
If (components! = Null)
{
Components. Dispose ();
}
Register (servicesname, strCurrPath );
}
}
# Register and uninstall the region service
// Register the service
Public void Register (string servicesname, string strServiceInstallPath)
{
IDictionary mySavedState = new Hashtable ();
Try
{
System. ServiceProcess. ServiceController service = new System. ServiceProcess. ServiceController (servicesname );
// Uninstall if the service already exists
If (ServiceIsExisted (servicesname ))
{
UnInstallService (servicesname, strCurrPath );
}
Service. Refresh ();
// Register the service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller ();
MySavedState. Clear ();
MyAssemblyInstaller. Path = "WSGPSServices.exe ";
MyAssemblyInstaller. UseNewContext = true;
MyAssemblyInstaller. Install (mySavedState );
MyAssemblyInstaller. Commit (mySavedState );
MyAssemblyInstaller. Dispose ();
Service. Start ();
ProcessStartInfo startinfo = new ProcessStartInfo ("WSGPSGateway.exe ");
Startinfo. WindowStyle = ProcessWindowStyle. Hidden;
Startinfo. Arguments = Application. StartupPath + "// WSGPSGateway.exe ";
Process. Start (startinfo );
InitializeComponent ();
}
Catch (Exception ex)
{
Throw new Exception ("error during service registration:" + ex. Message );
}
}
// Uninstall the service
Public void UnInstallService (string strServiceName, string strServiceInstallPath)
{
Try
{
If (ServiceIsExisted (servicesname ))
{
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller ();
MyAssemblyInstaller. UseNewContext = true;
MyAssemblyInstaller. Path = "WSGPSServices.exe ";
MyAssemblyInstaller. Uninstall (null );
MyAssemblyInstaller. Dispose ();
KillProcess ();
}
}
Catch (Exception ex)
{
Throw new Exception ("error occurred when uninstalling the service:" + ex. Message );
}
}
// End the process when the service is uninstalled
Private void KillProcess ()
{
System. Diagnostics. Process myproc = new System. Diagnostics. Process (); // obtain all open processes.
Try
{
Foreach (Process thisproc in Process. GetProcessesByName (Proceename ))
{
If (! Thisproc. CloseMainWindow ())
{
Thisproc. Kill ();
}
}
}
Catch (Exception Exc)
{
Throw Exc;
}
}
# Endregion
# Region start services and applications
// Start the service (if an existing service is started, an error will be reported if the service fails to be started in 30 seconds)
Public void StartService (string serviceName)
{
If (ServiceIsExisted (servicesname ))
{
System. ServiceProcess. ServiceController service = new System. ServiceProcess. ServiceController ("WSGPSServices ");
If (service. Status! = System. ServiceProcess. ServiceControllerStatus. Running & service. Status! = System. ServiceProcess. ServiceControllerStatus. StartPending)
{
Service. Start ();
For (int I = 0; I <30; I ++)
{
Service. Refresh ();
System. Threading. Thread. Sleep (1000 );
If (service. Status = System. ServiceProcess. ServiceControllerStatus. Running)
{
ProcessStartInfo startinfo = new ProcessStartInfo ("WSGPSGateway.exe ");
Startinfo. WindowStyle = ProcessWindowStyle. Hidden;
Startinfo. Arguments = Application. StartupPath + "// WSGPSGateway.exe ";
Process. Start (startinfo );
Break;
}
If (I = 29)
{
Throw new Exception ("WSGPS Services startup failed! ");
}
}
}
}
}
// Determine whether the service exists
Public bool ServiceIsExisted (string serviceName)
{
ServiceController [] services = ServiceController. GetServices ();
Foreach (ServiceController s in services)
{
If (s. ServiceName = servicesname)
{
Return true;
}
}
Return false;
}
# Endregion
# Region Timer scheduled task and Construction Method
// Timer Constructor
Private void InitializeComponent ()
{
This. components = new System. ComponentModel. Container ();
This. Timers = new System. Windows. Forms. Timer (this. components );
This. Timers. Enabled = true;
This. Timers. Interval = 180000;
This. Timers. Tick + = new System. EventHandler (this. Timers_Tick );
}
// Timer scheduled check task
Private void Timers_Tick (object sender, EventArgs e)
{
ServiceController [] services = ServiceController. GetServices ();
Foreach (ServiceController s in services)
{
If (s. ServiceName = servicesname)
{
Return; // null if return exists
}
Else
{
Register (servicesname, strCurrPath); // if no current service exists, Register the service again.
}
}
}
# Endregion
}
}

Related Article

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.