CreateService (advapi32)
Last changed: -84.110.53.106

.
Summary
Creates an NT service object and adds it to the specified service control manager database

C# Signature:

[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern IntPtr CreateService(
    IntPtr hSCManager,
    string lpServiceName,
    string lpDisplayName,
    uint dwDesiredAccess,
    uint dwServiceType,
    uint dwStartType,
    uint dwErrorControl,
    string lpBinaryPathName,
    string lpLoadOrderGroup,
    out uint lpdwTagId,
    string lpDependencies,
    string lpServiceStartName,
    string lpPassword);

VB Signature:

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function CreateService(ByVal hSCManager As IntPtr, ByVal serviceName As String, _
                ByVal displayName As String, ByVal desiredAccess As Int32, ByVal serviceType As Int32, _
                ByVal startType As Int32, ByVal errorcontrol As Int32, ByVal binaryPathName As String, _
                ByVal loadOrderGroup As String, ByVal TagBY As Int32, ByVal dependencides As String, _
                ByVal serviceStartName As String, ByVal password As String) As IntPtr

User-Defined Types:

None.

Notes:

The 4th parameter from the end, TagBY, should - accordig to the API documention, be a ByRef parameter. Unfortunately, the call only works if the parameter is ByVal.

lpDependencies, if not null, must be a series of strings concatenated with the null character as a delimiter, including a trailing one.

Tips & Tricks:

Please add some!

Sample Code:

Dim scHandle As IntPtr = OpenSCManager(Nothing, Nothing, SC_MANAGER_ALL_ACCESS)
    Dim serviceName As String = "AAATestService"
    Dim displayName As String = "AAATestDisplayName"

    If OpenFileDialog1.ShowDialog() <> DialogResult.OK Then
        MsgBox("aborting")
    End If

    Dim pathName As String = Chr(34) & OpenFileDialog1.FileName & Chr(34)

    Dim serviceHandle As IntPtr = CreateService(scHandle, serviceName, displayName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, _
                SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pathName, Nothing, 0, Nothing, Nothing, Nothing)
    If serviceHandle.Equals(IntPtr.Zero) Then
        MsgBox(Marshal.GetLastWin32Error())
    End If

    CloseServiceHandle(serviceHandle)
    CloseHandle(scHandle)

Alternative Managed API:

System.ServiceProcess.ServiceInstaller - http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemServiceProcessServiceInstallerClassTopic.asp

Documentation