Control and List Windows Services
As I whipped up my file synchronizing service application, to synchronize files between my computer and my NAS), I worked with the System.ServiceProcess Namespace. The System.ServiceProcess Namespace "provides classes that allow you to implement, install, and control Windows service applications".
My file synchronization needs did not require that my application service to be "running" all the time. In, fact I only needed the service to run under certain situations. It was easy enough to get the service written and installed and now I wanted to 'automatically' (programmatically) start and stop my service when certain conditions were met.
Entrance - the ServiceController Class. The ServiceController Class "Represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it." In order to get acclimated to the ServiceController Class I created a simple application to list and display information about the installed services.
using System;
using System.Windows.Forms;
using System.ServiceProcess;
namespace Services1
...{
public partial class Form1 : Form
...{
ServiceController controller;
public Form1()
...{
controller = new ServiceController();
controller.MachineName = ".";
InitializeComponent();
lstServices.DisplayMember = "DisplayName";
lstServices.ValueMember = "ServiceName";
lstServices.DataSource = ServiceController.GetServices();
}
private void StartService(string servicename)
...{
controller.ServiceName = servicename;
controller.Start();
}
private void PauseService(string servicename)
...{
controller.ServiceName = servicename;
if (controller.CanPauseAndContinue)
controller.Pause();
}
private void StopService(string servicename)
...{
controller.ServiceName = servicename;
if (controller.CanStop)
controller.Stop();
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
...{
if (lstServices.SelectedItems.Count > 0)
...{
try
...{
controller.ServiceName = lstServices.SelectedValue.ToString();
textBox1.Text = String.Format(
"Service Name: {0}\r\nDisplay Name: {1}\r\nType: {2}\r\nStatus: {3}",
controller.ServiceName,
controller.DisplayName,
controller.ServiceType.ToString(),
controller.Status.ToString()
);
}
catch (Exception ex)
...{
textBox1.Text = String.Format("Error: \r\n{0}",ex.Message);
}
}
else
...{
textBox1.Clear();
}
}
private void btnStart_Click(object sender, EventArgs e)
...{
StartService(lstServices.SelectedValue.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
...{
PauseService(lstServices.SelectedValue.ToString());
}
private void btnStop_Click(object sender, EventArgs e)
...{
StopService(lstServices.SelectedValue.ToString());
}
}
}