Stop and disable service

OSVBNET 1,386 Reputation points

I used this 2 lines to stop and disable startup of a service:

System.Diagnostics.Process.Start("SC", "Stop blah")
System.Diagnostics.Process.Start("SC", "Config blah Start=Disabled")

Using .net framework 4.7 I wanna do it this way (don't wanna use process/SC anymore):

Dim svc1 As New ServiceController("blah")
svc1.StartType = ServiceStartMode.Disabled

but StartType is read-only! any idea?

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,636 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 82,501 Reputation points

    ChangeServiceConfig works for me (as Admin, with a Manifest)

    Test with a random service :

        Dim scServices() As ServiceController  
        scServices = ServiceController.GetServices()  
        Dim scTemp As ServiceController  
        For Each scTemp In scServices  
            If scTemp.ServiceName = "XamlSpySvc" Then  
                Dim bRet As Boolean = ChangeServiceConfig(scTemp.ServiceHandle, CUInt(SERVICE_NO_CHANGE), SERVICE_DISABLED,  
                               SERVICE_NO_CHANGE, Nothing, Nothing, IntPtr.Zero, Nothing, Nothing, Nothing, Nothing)  
            End If  
        Next scTemp  

    with declarations :

    <DllImport("Advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>  
    Public Shared Function ChangeServiceConfig(<[In]()> ByVal hService As SafeHandle, ByVal dwServiceType As UInteger, ByVal dwStartType As UInteger, ByVal dwErrorControl As UInteger,  
                                                  <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpBinaryPathName As String, <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpLoadOrderGroup As String,  
                                                  ByVal lpdwTagId As IntPtr, <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpDependencies As String, <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpServiceStartName As String,  
                                                  <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpPassword As String, <[In](), MarshalAs(UnmanagedType.LPWStr)> ByVal lpDisplayName As String) As <MarshalAs(UnmanagedType.Bool)> Boolean  
    End Function  
    Public Const SERVICE_NO_CHANGE As UInteger = &HFFFFFFFFUI  
    Public Const SERVICE_BOOT_START = &H0  
    Public Const SERVICE_SYSTEM_START = &H1  
    Public Const SERVICE_AUTO_START = &H2  
    Public Const SERVICE_DEMAND_START = &H3  
    Public Const SERVICE_DISABLED = &H4  

2 additional answers

Sort by: Most helpful
  1. Dave Patrick 426.3K Reputation points MVP

    Another option may be to set the DWord service subkey registry Start value to 4

  2. OSVBNET 1,386 Reputation points

    ServiceController.ExecuteCommand maybe?!

    0 comments No comments