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

Controlling Installed Services via ServiceController in WinForms

5.00/5 (3 votes)
18 Feb 2016CPOL2 min read 18.6K   435  
Learn how to control Windows services via ServiceController in Windows Forms Application

Introduction

Here, I will simply explain how to control services installed in your machine via Windows Forms Application. The application will:

  • List and display all available services
  • Control a specific service
  • Display detailed service information

Background

  1. Intermediate knowledge of C#
  2. You should have some knowledge about Windows Forms

Requirements

  1. Visual Studio
  2. .NET Framework
  3. Windows machine

Using the Code

Step 1 - Designing Form

First, you must create a new Windows Forms Application from pre installed C# projects.

I called this project "ControlServices" .

Click on toolbox, then drag and drop 2 buttons, 2 listboxes, 2 textboxes and 4 labels into the Form Designer, as displayed in the image below:

Image 1

I would recommend to change button names in the properties. From toolbox controller, add a ServiceController item, then name it ServiceController1. In the service controller properties, select Appinfo as the default service name.

Image 2

Step 2 - Listing Services and Displaying Service Name

To display all installed services on the listBox2, first add the following double-click "List Services" button and add the following code:

C#
private void button2ListServices_Click(object sender, EventArgs e)
      {
          ServiceController[] AllServices; // creating an array of services
          AllServices = ServiceController.GetServices();// getting all services
          foreach (ServiceController oneService in AllServices)
          {
              listBox2.Items.Add(oneService.ServiceName.ToString());// inserting service names in
                                                                    // listbox one by one
          }
      }

Do not forget to add using System.ServiceProcess; namespace.

Here is a sample run of it:

Image 3

As you might notice, some services look meaningless, so we need to display full service name when the user clicks any service on listbox. To do this, double-click listbox2, and add the following code:

C#
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
           serviceController1.ServiceName = listBox2.SelectedItem.ToString();
            textBox2.Text = serviceController1.DisplayName.ToString();
        }

Image 4

E.g.: When user clicks ehSched service, the application displays its full name Windows Media Center Scheduler Service.

Step 3 - Controlling Services, Starting, Stopping and Pausing Them

We will control installed processes in this order.

If the selected process is stopped, we will try to start it, if it's running, we will try to pause it, if it's paused, we will try to stop it.

When the program fails to start, stop or pause a process, it will show an exception, saying that the task cannot be done.

Using using System.Threading; namespace is recommended, but not mandatory.

To implement the above application features, double-click listbox2 and add the following code:

C#
textBox1.BackColor = System.Drawing.Color.White;
textBox1.Text = serviceController1.Status.ToString();

Then go back to form designer and double-click Control Service button, and add the following code:

C#
private void button1ControlService_Click(object sender, EventArgs e)
      {
          if (this.serviceController1.Status.ToString() == "Stopped")
          {
            Thread.Sleep(2000);

              try // trying to start a service
              {
                  this.serviceController1.Start();
                  textBox1.Text = "Running";//serviceController1.Status.ToString();
                  textBox1.BackColor = System.Drawing.Color.Red;// change textbox color to red when
                  // process status is changed
              }
              catch (Exception) // exception thrown
              {
                  //handling exception
                  MessageBox.Show("Could not start this process",
                     "Process failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                  this.serviceController1.Close();
              }
          }

          else if (serviceController1.Status.ToString() == "Running")
          {
              Thread.Sleep(1500);
              try // trying to pause a service
              {
                  serviceController1.Pause();
                  textBox1.Text = serviceController1.Status.ToString();
              }
              catch (Exception)// exception thrown
              {
                  //handling exception
                  MessageBox.Show("Could not pause this process",
                          "Process failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

                  serviceController1.Close();
              }
          }

          else if(serviceController1.Status.ToString()=="Paused")
          {
              Thread.Sleep(1500); // trying to pause a service
              try
              {
                  serviceController1.Stop();
                  textBox1.Text = "Stopped";
                  textBox1.BackColor = System.Drawing.Color.Red;// change textbox color to red when
                  // process status is changed
              }

              catch (Exception)// exception thrown
              {
                  //handling exception
                  MessageBox.Show("Could not Stop this process",
                          "Process failed", MessageBoxButtons.OK, MessageBoxIcon.Error);

                  serviceController1.Close();
              }
          }

          else
          {
              Thread.Sleep(1000);
              serviceController1.Start();

              textBox1.BackColor = System.Drawing.Color.Red;// change textbox color to red when
                // process status is changed

              textBox1.Text = serviceController1.Status.ToString();
          }
          listBox1.Items.Add(serviceController1.ServiceName.ToString());
          // listing all services that we tried to change their status.
      }

Remember that the default service name that we chose is Appinfo. You might get an exception if you do not choose a service name in the service controller properties.

Image 5

Here are some application screenshots:

Image 6

Image 7

Hope this article helped you on how to control installed services.

Note

Do not hesitate to leave any comments or suggestions about this article.

License

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