运行exe文件作为Windows服务

时间:2013-10-21 13:03:02

标签: vb.net-2010

我有这个代码来运行我的应用程序作为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

1 个答案:

答案 0 :(得分:1)

不要重新发明轮子,请按照本教程为Windows服务创建安装程序:如何:Add Installers to Your Service Application

相关问题