Step 1: Form Objects
Create a simple Windows application form and add the below objects:
private System.Windows.Forms.ListBox lstServices;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnRestart;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.Label lblTrace;
After arranging the form objects:
Step 2: Load All Windows Services
On the form Load event, add this code to retrieve all Windows services to an array and use foreach
to add a service name to the list.
ServiceController[] allServices = ServiceController.GetServices();
foreach (ServiceController srv in allServices)
{
lstServices.Items.Add(srv.ServiceName);
}
Step 3: Form Actions
private void btnStart_Click(object sender, EventArgs e)
{
string strServiceName = "";
try
{
strServiceName = lstServices.SelectedItem.ToString();
ServiceController srv = new ServiceController(strServiceName);
if (srv.Status != ServiceControllerStatus.Running)
{
srv.Start();
}
}
catch (Exception ex)
{
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
string strServiceName = "";
try
{
strServiceName = lstServices.SelectedItem.ToString();
ServiceController srv = new ServiceController(strServiceName);
if (srv.Status != ServiceControllerStatus.Running)
{
srv.Refresh();
}
}
catch (Exception ex)
{
}
}
private void btnStop_Click(object sender, EventArgs e)
{
string strServiceName = "";
try
{
strServiceName = lstServices.SelectedItem.ToString();
ServiceController srv = new ServiceController(strServiceName);
if (srv.Status != ServiceControllerStatus.Stopped)
{
srv.Stop();
}
}
catch (Exception ex)
{
}
}
private void lstServices_Click(object sender, EventArgs e)
{
string strServiceName = "";
string strServiceStat = "";
try
{
strServiceName = (sender as ListBox).SelectedItem.ToString();
ServiceController srv = new ServiceController(strServiceName);
strServiceStat = srv.Status.ToString();
lblTrace.Text = strServiceName + " -> " + strServiceStat;
}
catch (Exception ex)
{
}
}