Click here to Skip to main content
13,559,559 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


10 bookmarked
Posted 21 Dec 2011
Licenced CPOL

Using the Service Controller in VB.NET

, 15 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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:


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:


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:

The Code

Below is the code used for this program:

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
    End Sub
    Private Sub IsServicePresent()
        Try Dim svcClass As ManagementClass = New ManagementClass("Win32_Service")

            For Each svcObj As ManagementObject In svcClass.GetInstances

            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
            If IsServiceRunning() = "Stopped" Then
                MsgBox("The Service MsMpSvc Is Already Stopped", _
                  MsgBoxStyle.Information, "Service Status")
            ElseIf IsServiceRunning() = "Running" Then
            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
            If IsServiceRunning() = "Running" Then
                MsgBox("The Service MsMpSvc Is Already Running", _
                   MsgBoxStyle.Information, "Service Status")
            ElseIf IsServiceRunning() = "Stopped" Then
            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

    End Sub
    Private Function IsServiceRunning()

        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.


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.


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


About the Author

CEO PC's Xcetra
United States United States
My first experience with computers was when my mom gave a Timex Sinclair 1000 to me for Christmas some time in the late 70's (I still have it)There I learned to copy code from magazines to save to cassette tapes for playing games.

Since then I have dabbled in:
Basic,Qbasic,ruby,python,Java Script, HTML, CSS, C#, C++, Perl, and a few other I can't think of off hand.
Now I Mainly work with VB Script and VB.Net
I Prefer to build programs that make use of the GUI so I don't have to remember all of the syntax for console apps. I realy don't care much for HTML because of the way you build and then run to see if it looks right. Also the new WPF is to much like HTML so I steer clear of it for now.
Most of what I build is for getting information from a system to use in system repair.I make heavy use of the WMI classes. Why reinvent something.

You may also be interested in...


Comments and Discussions

QuestionRunAs Administrator? Pin
rht34116-Nov-12 4:34
memberrht34116-Nov-12 4:34 
GeneralRe: RunAs Administrator? Pin
ledtech316-Nov-12 4:49
memberledtech316-Nov-12 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02-2016 | 2.8.180527.1 | Last Updated 16 Nov 2012
Article Copyright 2011 by ledtech3
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid