2013-10-21 31 views
-1

我有这段代码来运行我的应用程序作为windows服务,但它不起作用我不知道是什么问题。这是我的代码:运行一个exe文件作为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 
+0

什么是不工作?任何错误?你可以添加到你的问题? – rene

回答

1

而不是重新发明轮子,按照这个教程来为你的Windows服务的安装:如何:Add Installers to Your Service Application

+0

感谢您的回答,但我希望此代码能够工作 –

+0

没有错误,但我的应用程序没有添加到服务管理器,并且在重新启动后没有运行 –

相关问题