Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

OpenService (advapi32)
 
.
Summary
The OpenService function opens an existing service.

C# Signature:

[DllImport("advapi32.dll", EntryPoint = "OpenServiceA", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess);
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);

VB Signature:

<DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function OpenService(ByVal hSCManager As IntPtr, ByVal lpServiceName As String, ByVal dwDesiredAccess As Int32) As IntPtr
    End Function

VB .NET Signature:

    Declare Function OpenService Lib "advapi32.dll" Alias "OpenServiceA" (ByVal hSCManager As IntPtr, ByVal lpServiceName As String, ByVal dwDesiredAccess As Integer) As IntPtr

User-Defined Types:

SERVICE_ACCESS

Notes:

Seems the CharSet should be Ansi, not Auto.

Also the code from a sample did not work for me, so I used the following code to open a service:

    IntPtr service = OpenService(scman, ServiceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus);
    if (service == IntPtr.Zero)
      throw new Win32Exception(Marshal.GetLastWin32Error());

None.

Tips & Tricks:

Please add some!

Sample Code:

The following sample opens the service with privileges to stop and delete it:

    IntPtr hService = OpenService(hSCM, ServiceName, ((uint)SERVICE_ACCESS.SERVICE_STOP |

IntPtr hService = OpenService(hSCM, ServiceName,

                ((uint)SERVICE_ACCESS.SERVICE_STOP |
                (uint)System.Messaging.StandardAccessRights.Delete));

Alternative Managed API:

Unless you are going use EnumDependentServices API please use 'System.ServiceProcess.ServiceController' that is provided in the framework.

Documentation
OpenService on MSDN

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions