Solved

Start/Stop Windows Service

Posted on 2001-08-15
9
329 Views
Last Modified: 2012-06-27
How can I Start/Stop Windows Service using VB?
/Xavier
0
Comment
Question by:folletxavier
9 Comments
 
LVL 43

Accepted Solution

by:
TimCottee earned 51 total points
ID: 6388707
Public Declare Function OpenService Lib "advapi32.dll" Alias "OpenServiceA" (ByVal hSCManager As Long, ByVal lpServiceName As String, ByVal dwDesiredAccess As Long) As Long
Public Declare Function OpenSCManager Lib "advapi32.dll" Alias "OpenSCManagerA" (ByVal lpMachineName As String, ByVal lpDatabaseName As String, ByVal dwDesiredAccess As Long) As Long
Public Declare Function QueryServiceStatus Lib "advapi32.dll" (ByVal hService As Long, lpServiceStatus As SERVICE_STATUS) As Long
Public Declare Function ControlService Lib "advapi32.dll" (ByVal hService As Long, ByVal dwControl As Long, lpServiceStatus As SERVICE_STATUS) As Long
Public Declare Function StartService Lib "advapi32.dll" Alias "StartServiceA" (ByVal hService As Long, ByVal dwNumServiceArgs As Long, ByVal lpServiceArgVectors As Long) As Long
Public Declare Function CloseServiceHandle Lib "advapi32.dll" (ByVal hSCObject As Long) As Long

Const STANDARD_RIGHTS_REQUIRED = &HF0000
Const STANDARD_RIGHTS_ALL = &H1F0000
Const SPECIFIC_RIGHTS_ALL = &HFFFF

' Service database names
Const SERVICES_ACTIVE_DATABASE = "ServicesActive"
Const SERVICES_FAILED_DATABASE = "ServicesFailed"

' Value to indicate no change to an optional parameter
Const SERVICE_NO_CHANGE = &HFFFF

' Service State -- for Enum Requests (Bit Mask)
Const SERVICE_ACTIVE = &H1
Const SERVICE_INACTIVE = &H2
Const SERVICE_STATE_ALL = (SERVICE_ACTIVE Or SERVICE_INACTIVE)

' Controls
Const SERVICE_CONTROL_STOP = &H1
Const SERVICE_CONTROL_PAUSE = &H2
Const SERVICE_CONTROL_CONTINUE = &H3
Const SERVICE_CONTROL_INTERROGATE = &H4
Const SERVICE_CONTROL_SHUTDOWN = &H5

' Service State -- for CurrentState
Const SERVICE_STOPPED = &H1
Const SERVICE_START_PENDING = &H2
Const SERVICE_STOP_PENDING = &H3
Const SERVICE_RUNNING = &H4
Const SERVICE_CONTINUE_PENDING = &H5
Const SERVICE_PAUSE_PENDING = &H6
Const SERVICE_PAUSED = &H7

' Controls Accepted  (Bit Mask)
Const SERVICE_ACCEPT_STOP = &H1
Const SERVICE_ACCEPT_PAUSE_CONTINUE = &H2
Const SERVICE_ACCEPT_SHUTDOWN = &H4

' Service Control Manager object specific access types
Const SC_MANAGER_CONNECT = &H1
Const SC_MANAGER_CREATE_SERVICE = &H2
Const SC_MANAGER_ENUMERATE_SERVICE = &H4
Const SC_MANAGER_LOCK = &H8
Const SC_MANAGER_QUERY_LOCK_STATUS = &H10
Const SC_MANAGER_MODIFY_BOOT_CONFIG = &H20

Const SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or SC_MANAGER_CONNECT Or SC_MANAGER_CREATE_SERVICE Or SC_MANAGER_ENUMERATE_SERVICE Or SC_MANAGER_LOCK Or SC_MANAGER_QUERY_LOCK_STATUS Or SC_MANAGER_MODIFY_BOOT_CONFIG)

' Service object specific access type
Const SERVICE_QUERY_CONFIG = &H1
Const SERVICE_CHANGE_CONFIG = &H2
Const SERVICE_QUERY_STATUS = &H4
Const SERVICE_ENUMERATE_DEPENDENTS = &H8
Const SERVICE_START = &H10
Const SERVICE_STOP = &H20
Const SERVICE_PAUSE_CONTINUE = &H40
Const SERVICE_INTERROGATE = &H80
Const SERVICE_USER_DEFINED_CONTROL = &H100
Const SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or SERVICE_QUERY_CONFIG Or SERVICE_CHANGE_CONFIG Or SERVICE_QUERY_STATUS Or SERVICE_ENUMERATE_DEPENDENTS Or SERVICE_START Or SERVICE_STOP Or SERVICE_PAUSE_CONTINUE Or SERVICE_INTERROGATE Or SERVICE_USER_DEFINED_CONTROL)

Public Type SERVICE_STATUS
    dwServiceType As Long
    dwCurrentState As Long
    dwControlsAccepted As Long
    dwWin32ExitCode As Long
    dwServiceSpecificExitCode As Long
    dwCheckPoint As Long
    dwWaitHint As Long
End Type
 
Public Function QueryService(strServiceName As String, strServerName As String) As String
    App.LogEvent "QueryService : " & strServiceName
    Dim lngSMHandle As Long
    Dim lngSvcHandle As Long
    Dim ssStatus As SERVICE_STATUS
    lngSMHandle = OpenSCManager(strServerName, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT)
    lngSvcHandle = OpenService(lngSMHandle, strServiceName, SERVICE_ALL_ACCESS)
    ret = QueryServiceStatus(lngSvcHandle, ssStatus)
    If lngSvcHandle = 0& Then QueryService = "Service Not Found"
    Select Case ssStatus.dwCurrentState
    Case SERVICE_STOPPED
        QueryService = "Service Is Stopped"
    Case SERVICE_START_PENDING
        QueryService = "Service Start Pending"
    Case SERVICE_STOP_PENDING
        QueryService = "Service Stop Pending"
    Case SERVICE_RUNNING
        QueryService = "Service Is Running"
    Case SERVICE_CONTINUE_PENDING
        QueryService = "Service Continue Pending"
    Case SERVICE_PAUSE_PENDING
        QueryService = "Service Pause Pending"
    Case SERVICE_PAUSED
        QueryService = "Service Paused"
    End Select
    CloseServiceHandle lngSvcHandle
    CloseServiceHandle lngSMHandle
End Function

Public Sub StopSvc(strServiceName As String, strServerName As String)
    App.LogEvent "Stop Service : " & strServiceName
    Dim lngSMHandle As Long
    Dim lngSvcHandle As Long
    Dim ssStatus As SERVICE_STATUS
    lngSMHandle = OpenSCManager(strServerName, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT)
    lngSvcHandle = OpenService(lngSMHandle, strServiceName, SERVICE_ALL_ACCESS)
    ret = QueryServiceStatus(lngSvcHandle, ssStatus)
    If lngSvcHandle <> 0& Then
        ControlService lngSvcHandle, SERVICE_CONTROL_STOP, ssStatus
    End If
    CloseServiceHandle lngSvcHandle
    CloseServiceHandle lngSMHandle
End Sub

Public Sub StartSvc(strServiceName As String, strServerName As String)
    App.LogEvent "Start Service : " & strServiceName
    Dim lngSMHandle As Long
    Dim lngSvcHandle As Long
    Dim ssStatus As SERVICE_STATUS
    lngSMHandle = OpenSCManager(strServerName, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT)
    lngSvcHandle = OpenService(lngSMHandle, strServiceName, SERVICE_ALL_ACCESS)
    ret = QueryServiceStatus(lngSvcHandle, ssStatus)
    If lngSvcHandle <> 0& Then
        StartService lngSvcHandle, 0&, 0&
    End If
    CloseServiceHandle lngSvcHandle
    CloseServiceHandle lngSMHandle
End Sub

Public Sub Main()
    frmPager.Show
End Sub
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 6388711
Sorry, forgot to add the comments, you can skip the Sub Main that is irrelevant to you. You can supply either an empty string or a valid server name to control/query the service on a local or remote machine.
0
 
LVL 3

Expert Comment

by:czpczp
ID: 6388762
How 'bout

Shell "cmd.exe /c net start ServiceName"

or

Shell "cmd.exe /c net stop ServiceName"


Wher ServiceName is the name of the service you wish to toggle.
0
 
LVL 3

Expert Comment

by:czpczp
ID: 6388802
You can use variables in the above too:


Dim SrvName

SrvName="ServiceName"


Shell "cmd.exe /c net stop " & SrvName

or

Shell "cmd.exe /c net start " & SrvName
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 3

Expert Comment

by:czpczp
ID: 6388954
If the above is something you may consider using, it can also be run hidden using:


RetVal = Shell("cmd.exe /c net start " & SrvName, vbHide)
0
 
LVL 3

Expert Comment

by:czpczp
ID: 6388983
Actually, you don't need to include the "cmd /c" (in my last post)

RetVal = Shell("net stop " & SrvName, vbHide)
0
 
LVL 3

Expert Comment

by:Corvax021899
ID: 6391301
Or you could use the ADSI function...
1- Make a Reference to Active DS Type Library in VB

Make a Module Like This:

Public function Stop_NT_Service(ServiceName as string,ComputerName as String)

Dim oServer As IADsComputer
Dim oServiceOp As IADsServiceOperations

Set oServer = GetObject("WinNT://" & ComputerName)
Set oServiceOp = oServer.GetObject("Service", ServiceName)

If oServiceOp.status = ADS_SERVICE_RUNNING Then oServiceOp.Stop
End Function

Public function Start_NT_Service(ServiceName as string,ComputerName as String)

Dim oServer As IADsComputer
Dim oServiceOp As IADsServiceOperations

Set oServer = GetObject("WinNT://" & ComputerName)
Set oServiceOp = oServer.GetObject("Service", ServiceName)

If Not oServiceOp.status = ADS_SERVICE_RUNNING Then oServiceOp.Start

End Function



0
 

Author Comment

by:folletxavier
ID: 6391758
czpczp:
I really like you code, simple and working... But TimCottee's let me be in better control.
Thank you all!
/Xavier
0
 
LVL 2

Expert Comment

by:prosit
ID: 8262025
very nice piece of code TimCottee, thanks

j
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now