Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Manage All Windows Services

4.52/5 (7 votes)
21 Aug 2011CPOL 11.9K  
This article shows to how to manage Windows services for beginners.

Step 1: Form Objects


Create a simple Windows application form and add the below objects:


C#
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.


C#
ServiceController[] allServices = ServiceController.GetServices();
foreach (ServiceController srv in allServices)
{
    lstServices.Items.Add(srv.ServiceName);
}

Step 3: Form Actions


C#
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)
    {
        //
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)