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

Using the Service Controller in VB.NET

5.00/5 (2 votes)
15 Nov 2012CPOL4 min read 52.5K  
How to use the service controller in VB.NET

Using the service controller is really very easy.

All of my applications come about from something I’m working on at the time. This time, I needed a way for my mom to temporarily stop the Microsoft Security Essentials service which is named “MsMpSvc”. There was no built-in way that I could find. As with all AV/Antimalware programs, they sometimes hog system resources and on a single core processor, it is really bad.

The normal way a person would stop a service is through the admin services utility. And depending on how a system is set up would allow for different ways to get there.

While looking to see if something was already made to do the job that I wanted to do, I ran across a help page that suggested to use the Service Controller for the project.

The service controller is located in the (I’m using the 2008 standard edition) Visual Studio Tools under the Components section. It has been a while since I first used one of these so I had to relearn how to use it.

Here is what the completed program looks like:

MSAVstoper

This program is really bare minimum and took about 3 hours to build and test (a couple more later to update). As you can see, I have the start and stop buttons for the service. I could have stopped there but I also added the message at the top to tell the user if the service was actually installed or not. I used the list of installed services as a quick way to check for the service name to see if it was actually installed or not. I probably could have used a collection of services, then checked that, but I didn’t think of it at the time. So we get a list of installed services as a bonus.

Here is what the program looks like inside of Visual Studio:

MsstoppinVS

We need to add 5 labels, 2 buttons, and 1 list box to the form giving everything a name. Next, we add the Imports statements to the code section for Imports System, Imports System.Management then add the reference for System. I like to add a label and an About box to the project so I can verify my versions as I’m building and testing. This can be handy later when an end user has a question and you can have them give you the version they are using. Next, we add the Service Control Module and set the property ServiceName: to MsMpSvc, as you can see below:

Image 3

The Code

Below is the code used for this program:

VB.NET
Imports System
Imports System.Management
Imports System.ServiceProcess
Imports System.Diagnostics

Public Class Form1
    Private SvcStatus As String Private Sub Form1_Load(ByVal sender As _
            System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        IsServicePresent()
    End Sub
    Private Sub IsServicePresent()
        Try Dim svcClass As ManagementClass = New ManagementClass("Win32_Service")

            For Each svcObj As ManagementObject In svcClass.GetInstances
                ListBoxInstalledServices.Items.Add(svcObj.Item("Name"))

            Next If ListBoxInstalledServices.Items.Contains("MsMpSvc") = True Then
                lblServiceExist.Text = "The Service MsMpSvc Exist"
                lblServiceExist.ForeColor = Color.DarkSeaGreen
            ElseIf ListBoxInstalledServices.Items.Contains("MsMpSvc") = False Then
                lblServiceExist.Text = "The Service MsMpSvcDoes Not Exist " & _
                      vbNewLine & "You Can Not Use This Program To Control The Service MsMpSvc"
                lblServiceExist.ForeColor = Color.DarkRed
                btnStartService.Enabled = False
                btnStopService.Enabled = False End If Catch ex As Exception
            MsgBox("Error" & vbNewLine & ex.Message.ToString, _
               MsgBoxStyle.Information, "Error Service Verification")
        End Try
      End Sub
      Private Sub btnStopService_Click(ByVal sender As System.Object, _
              ByVal e As System.EventArgs) Handles btnStopService.Click
        Try
            If IsServiceRunning() = "Stopped" Then
                MsgBox("The Service MsMpSvc Is Already Stopped", _
                  MsgBoxStyle.Information, "Service Status")
            ElseIf IsServiceRunning() = "Running" Then
                ServiceController1.Stop()
            End If
            ' the Service is already named in the property
            ' of the ServiceControl module Catch ex As Exception
            MsgBox("An Error Occurred While Trying to Stop the Service" & _
               vbNewLine & ex.Message.ToString, MsgBoxStyle.Information, _
               "Stop Service Error")
        End Try
      End Sub
      Private Sub btnStartService_Click(ByVal sender As System.Object, _
              ByVal e As System.EventArgs) Handles btnStartService.Click
        Try
            If IsServiceRunning() = "Running" Then
                MsgBox("The Service MsMpSvc Is Already Running", _
                   MsgBoxStyle.Information, "Service Status")
            ElseIf IsServiceRunning() = "Stopped" Then
                ServiceController1.Start()
            End If
        Catch ex As Exception
            MsgBox("Error While Trying to Start The Service" & vbNewLine & _
              ex.Message.ToString, MsgBoxStyle.Information, "Start Service Error")
        End Try
      End Sub
      Private Sub lblAbout_Click(ByVal sender As System.Object, _
                 ByVal e As System.EventArgs) Handles lblAbout.Click
        AboutBox1.Show()

    End Sub
    Private Function IsServiceRunning()

        ServiceController1.Refresh()
        SvcStatus = ServiceController1.Status().ToString

        Return SvcStatus

    End Function
End Class

In the Form Load section, we pass off to a Sub called IsServicePresent(). We then fill the list box and check if the service we want is listed. If Yes, then we set the label text and the color to 1 message, “ElseIf” No, then we set the label text and color to another message. All before the form gets loaded. I also updated the code to disable the buttons if the service is not present. I use ElseIf to be sure the argument gets evaluated to True or False.

Once the Form is loaded, then it is just a matter for the user to click start or stop. Note that the service could take up to around 20 seconds to start or stop the service depending on the system. The user will know when this happens as the alert in the notification area will pop up and turn red with a warning and then turn green after the service is restarted.

That’s pretty much it for the program as it stands.

It does need more code to handle:

1. One thing I haven’t figured out how to do is to check if a status is pending for starting or stopping. I was able to add for if the program was started or stopped already though. Everything I tried broke the program when trying to check for pending status. Possibly add a timer to keep checking every few seconds what the status is.

FYI: This service does not show up on the Windows 8 Developers preview. I tested this and a few other programs on it.

Note

As of 11-15-2012, this app no longer works on Windows Vista or with Windows 7 with all of the current security updates installed. It is returning a Inner Exception message of "Access Denied".

I have added the "requireAdministrator" to the manifest, and added a self signing cert to the project and still get the error. I am still looking into the cause.

License

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