-1

我有这段代码可以将我的应用程序作为 Windows 服务运行,但它不起作用我不知道是什么问题。这是我的代码:

Module Module1
Private Const GENERIC_ALL As Long = &H10000000
Private Const SERVICES_ACTIVE_DATABASE As String = "ServicesActive"
Private Const SERVICE_AUTO_START As Long = &H2
Private Const SERVICE_ERROR_IGNORE As Long = &H0
Private Const SERVICE_INTERACTIVE_PROCESS As Long = &H100
Private Const SERVICE_WIN32_OWN_PROCESS As Long = &H10

Private Declare Function CloseServiceHandle Lib "advapi32.dll" (ByVal hSCObject As Long) As Long
Private Declare Function CreateService Lib "advapi32.dll" Alias "CreateServiceA" (ByVal hSCManager As Long, ByVal lpServiceName As String, ByVal lpDisplayName As String, ByVal dwDesiredAccess As Long, ByVal dwServiceType As Long, ByVal dwStartType As Long, ByVal dwErrorControl As Long, ByVal lpBinaryPathName As String, ByVal lpLoadOrderGroup As String, ByRef lpdwTagId As Long, ByVal lpDependencies As String, ByVal lp As String, ByVal lpPassword As String) As Long
Private Declare Function GetLastError Lib "kernel32.dll" () As Long
Private Declare Function OpenSCManager Lib "advapi32.dll" Alias "OpenSCManagerA" (ByVal lpMachineName As String, ByVal lpDatabaseName As String, ByVal dwDesiredAccess As Long) As Long

Sub main()
    Dim hSCM As Long
    Dim hSrv As Long
    Dim ret As String
    ' attempts to recieve a handle for the Service Control Manager
    ' if the attempt fails display an error message and end the program
    ' else attempt to create a service
    hSCM = OpenSCManager("", SERVICES_ACTIVE_DATABASE, GENERIC_ALL)
    If hSCM = 0 Then
        ret = MsgBox("OpenSCManager failed. " & GetLastError(), vbCritical, "Error")
        End
    Else
        ' attempt to create a service if the function fails display an error message
        ' and end else display that the service has been added
        hSrv = CreateService(hSCM, "LocalSystemCMD", "DisplayNameCMD", GENERIC_ALL, SERVICE_WIN32_OWN_PROCESS Or SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, "C:\test.exe", vbNullString, 0&, vbNullString, vbNullString, vbNullString)
        If hSrv = 0 Then
            ret = MsgBox("CreateService failed. " & GetLastError(), vbCritical, "Error")
            End
        Else
            ret = MsgBox("Service added.", vbInformation, "Service Added")
        End If
    End If
    'cleanup
    CloseServiceHandle(ret)
    CloseServiceHandle(hSCM)

    End ' end the program
End Sub
End Module
4

1 回答 1

1

与其重新发明轮子,不如按照本教程为您的 Windows 服务创建安装程序:如何:将安装程序添加到您的服务应用程序

于 2013-10-21T13:08:55.070 回答