'* ************************************************************** *
'* 程序名称:modNtSrv
'* 程序功能:实现NT服务
'* 作者:lyserver
'* 联系方式:http://blog.csdn.net/lyserver
'* ************************************************************** *
Option Explicit
'服务控制常量
Public Enum SERVICE_CONTROL
SERVICE_CONTROL_STOP = 1&
SERVICE_CONTROL_PAUSE = 2&
SERVICE_CONTROL_CONTINUE = 3&
SERVICE_CONTROL_INTERROGATE = 4&
SERVICE_CONTROL_SHUTDOWN = 5&
End Enum
'服务状态常量
Public Enum SERVICE_STATE
SERVICE_STOPPED = &H1
SERVICE_START_PENDING = &H2
SERVICE_STOP_PENDING = &H3
SERVICE_RUNNING = &H4
SERVICE_CONTINUE_PENDING = &H5
SERVICE_PAUSE_PENDING = &H6
SERVICE_PAUSED = &H7
Delete = &H10000
End Enum
'服务启动方式常量
Public Const SERVICE_SYSTEM_START As Long = &H1
Public Const SERVICE_AUTO_START As Long = &H2
Public Const SERVICE_DEMAND_START As Long = &H3
'服务错误控制级别
Private Const SERVICE_ERROR_NORMAL As Long = &H1
'SCM权限常量
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const SC_MANAGER_CONNECT = &H1
Public Const SC_MANAGER_CREATE_SERVICE = &H2
Public Const SC_MANAGER_ENUMERATE_SERVICE = &H4
Public Const SC_MANAGER_LOCK = &H8
Public Const SC_MANAGER_QUERY_LOCK_STATUS = &H10
Public Const SC_MANAGER_MODIFY_BOOT_CONFIG = &H20
Public Const SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or SC_MANAGER_CONNECT Or SC_MANAGER_CREATE_SERVICE Or SC_MANAGER_ENUMERATE_SERVICE Or SC_MANAGER_LOCK Or SC_MANAGER_QUERY_LOCK_STATUS Or SC_MANAGER_MODIFY_BOOT_CONFIG)
'接受SCP控制消息常量
Public Const SERVICE_ACCEPT_STOP As Long = &H1
Public Const SERVICE_ACCEPT_PAUSE_CONTINUE As Long = &H2
Public Const SERVICE_ACCEPT_SHUTDOWN As Long = &H4
'服务权限常量
Public Const SERVICE_QUERY_CONFIG = &H1
Public Const SERVICE_CHANGE_CONFIG = &H2
Public Const SERVICE_QUERY_STATUS = &H4
Public Const SERVICE_ENUMERATE_DEPENDENTS = &H8
Public Const SERVICE_START = &H10
Public Const SERVICE_STOP = &H20
Public Const SERVICE_PAUSE_CONTINUE = &H40
Public Const SERVICE_INTERROGATE = &H80
Public Const SERVICE_USER_DEFINED_CONTROL = &H100
Public Const SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or SERVICE_QUERY_CONFIG Or SERVICE_CHANGE_CONFIG Or SERVICE_QUERY_STATUS Or SERVICE_ENUMERATE_DEPENDENTS Or SERVICE_START Or SERVICE_STOP Or SERVICE_PAUSE_CONTINUE Or SERVICE_INTERROGATE Or SERVICE_USER_DEFINED_CONTROL)
'服务类型常量
Public Const SERVICE_WIN32_OWN_PROCESS As Long = &H10
Public Const SERVICE_WIN32_SHARE_PROCESS As Long = &H20
Public Const SERVICE_INTERACTIVE_PROCESS As Long = &H100
Public Const SERVICE_WIN32 As Long = SERVICE_WIN32_OWN_PROCESS + SERVICE_WIN32_SHARE_PROCESS
'辅助常量
Public Const ERROR_SERVICE_SPECIFIC_ERROR = 1066&
Public Const ERROR_SERVICE_EXISTS = 1073&
Public Const SERVICES_ACTIVE_DATABASE = "ServicesActive"
Public Const NO_ERROR = 0 ' dderror
Public Type SERVICE_TABLE_ENTRY
lpServiceName As Long
lpServiceProc As Long
lpServiceNameNull As Long
lpServiceProcNull As Long
End Type
Public Type SERVICE_STATUS
dwServiceType As Long
dwCurrentState As Long
dwControlsAccepted As Long
dwWin32ExitCode As Long
dwServiceSpecificExitCode As Long
dwCheckPoint As Long
dwWaitHint As Long
End Type
'NT服务API
Public Declare Function OpenSCManager Lib "advapi32.dll" Alias "OpenSCManagerW" (ByVal lpMachineName As String, ByVal lpDatabaseName As String, ByVal dwDesiredAccess As Long) As Long
Public Declare Function CloseServiceHandle Lib "advapi32.dll" (ByVal hSCObject As Long) As Long
Public Declare Function OpenService Lib "advapi32.dll" Alias "OpenServiceW" (ByVal hSCManager As Long, ByVal lpServiceName As String, ByVal dwDesiredAccess As Long) As Long
Public Declare Function DeleteService Lib "advapi32.dll" (ByVal hService As Long) As Long
Public Declare Function ControlService Lib "advapi32.dll" (ByVal hService As Long, ByVal dwControl As Long, lpServiceStatus As SERVICE_STATUS) As Long
Public Declare Function QueryServiceStatus Lib "advapi32.dll" (ByVal hService As Long, lpServiceStatus As SERVICE_STATUS) As Long
Public Declare Function CreateService Lib "advapi32.dll" Alias "CreateServiceW" (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, lpdwTagId As Long, ByVal lpDependencies As String, ByVal lp As String, ByVal lpPassword As String) As Long
Public Declare Function StartService Lib "advapi32.dll" Alias "StartServiceW" (ByVal hService As Long, ByVal dwNumServiceArgs As Long, ByVal lpServiceArgVectors As Long) As Long
Public Declare Function StartServiceCtrlDispatcher Lib "advapi32.dll" Alias "StartServiceCtrlDispatcherW" (lpServiceStartTable As SERVICE_TABLE_ENTRY) As Long
Public Declare Function RegisterServiceCtrlHandler Lib "advapi32.dll" Alias "RegisterServiceCtrlHandlerW" (ByVal lpServiceName As Long, ByVal lpHandlerProc As Long) As Long
Public Declare Function SetServiceStatus Lib "advapi32.dll" (ByVal hServiceStatus As Long, lpServiceStatus As SERVICE_STATUS) As Long
'错误处理API
Public Declare Function GetLastError Lib "kernel32" () As Long
'线程API
Public Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Long, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Public Declare Function ResumeThread Lib "kernel32" (ByVal hThread As Long) As Long
Public Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long, ByVal dwExitCode As Long) As Long
Public Declare Function GetCurrentThread Lib "kernel32" () As Long
Public Declare Function GetCurrentThreadId Lib "kernel32" () As Long
'COM API
Public Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Public IID_IDispatch As GUID
Public Declare Function CoMarshalInterThreadInterfaceInStream Lib "ole32.dll" (riid As GUID, ByVal pUnk As IUnknown, ppStm As Long) As Long
Declare Function CoGetInterfaceAndReleaseStream Lib "ole32.dll" (ByVal pStm As Long, riid As GUID, pUnk As IUnknown) As Long
Public Declare Function CoInitialize Lib "ole32.dll" (ByVal pvReserved As Long) As Long
Public Declare Sub CoUninitialize Lib "ole32.dll" ()
'消息处理API
Public Declare Function GetMessage Lib "user32" Alias "GetMessageA" (lpMsg As MSG, ByVal hwnd As Long, ByVal wMsgFilterMin As Long, ByVal wMsgFilterMax As Long) As Long
Public Declare Function PeekMessage Lib "user32" Alias "PeekMessageA" (lpMsg As MSG, ByVal hwnd As Long, ByVal wMsgFilterMin As Long, ByVal wMsgFilterMax As Long, ByVal wRemoveMsg As Long) As Long
Public Const PM_REMOVE As Long = &H1
Public Declare Function DispatchMessage Lib "user32" Alias "DispatchMessageA" (lpMsg As MSG) As Long
Public Declare Function TranslateMessage Lib "user32" (lpMsg As MSG) As Long
Public Const WM_QUIT As Long = &H12
Public Declare Function PostThreadMessage Lib "user32" Alias "PostThreadMessageA" (ByVal idThread As Long, ByVal MSG As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Type MSG
hwnd As Long
message As Long
wParam As Long
lParam As Long
time As Long
pt As Currency
End Type
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
'响铃API
Public Declare Function MessageBeep Lib "user32" (ByVal wType As Long) As Long
Public Const MB_ICONEXCLAMATION = &H30&
Public Const MB_ICONQUESTION = &H20&
Public Declare Function GetTickCount Lib "kernel32" () As Long
'=======================================================
' 模块公用变量
'=======================================================
Private Const SERVICE_NAME As String = "MyNTService" '服务名称
Private Const DISPLAY_NAME As String = "My NT Service" '服务显示名称
Private m_szServiceName As String
Private m_szDisplayName As String
Private m_status As SERVICE_STATUS
Private m_hServiceStatus As Long
Private m_dwMainThreadId As Long, m_dwServiceThreadId
Private m_hServiceThread As Long
'=======================================================
' 函数名称:Main
' 函数说明:主程序入口点
'=======================================================
Sub Main()
'处理命令行参数
Dim szArgv As String
szArgv = UCase(Trim(Command))
If Left(szArgv, 1) = "/" Or Left(szArgv, "1") = "-" Then
szArgv = Mid(szArgv, 2)
End If
'转换变量本地系统编码
m_szServiceName = StrConv(SERVICE_NAME, vbUnicode)
m_szDisplayName = StrConv(SERVICE_NAME, vbUnicode)
'如果有参数,则进行处理
If Len(szArgv) > 0 Then
If szArgv = "I" Or szArgv = "INSTALL" Or szArgv = "REGSERVER" Then
'安装服务
If Install() Then
MsgBox vbCrLf & "服务已被成功安装!" & vbCrLf, vbInformation, "提示"
Else
MsgBox vbCrLf & "服务安装失败!" & vbCrLf, vbExclamation, "提示"
End If
Exit Sub
ElseIf szArgv = "U" Or szArgv = "UNINSTALL" Or szArgv = "UNREGSERVER" Then
'卸载服务
If Uninstall() Then
MsgBox vbCrLf & "服务已被成功卸载!" & vbCrLf, vbInformation, "提示"
Else
MsgBox vbCrLf & "服务卸载失败!" & vbCrLf, vbExclamation, "提示"
End If
Exit Sub
Else
MsgBox vbCrLf & "不支持的参数,终止运行!", vbCritical, "警告"
Exit Sub
End If
End If
'无参数时,判断服务是否已被安装,否则退出
If Not IsInstalled Then Exit Sub
'获得主线程ID以备用
m_dwMainThreadId = GetCurrentThreadId()
'尝试启动服务
Dim result As Long
Dim ste As SERVICE_TABLE_ENTRY
ste.lpServiceName = StrPtr(m_szServiceName)
ste.lpServiceProc = GetFuncAddr(AddressOf ServiceMain)
result = StartServiceCtrlDispatcher(ste)
'如果服务成功启动,则进入消息循环待
If result <> 0 Then
Dim uMsg As MSG
Do While GetMessage(uMsg, 0, 0, 0)
Loop
End If
'等待服务线程结束
WaitForSingleObject m_hServiceThread, 800
End Sub
'=======================================================
' 函数名称:IsInstalled
' 函数说明:判断服务是否已安装
'=======================================================
Public Function IsInstalled() As Boolean
Dim bSuccess As Long
Dim hSCM As Long, hService As Long
hSCM = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
If hSCM <> 0 Then
hService = OpenService(hSCM, m_szServiceName, SERVICE_QUERY_CONFIG)
If hService <> 0 Then
bSuccess = True
Call CloseServiceHandle(hService)
End If
Call CloseServiceHandle(hSCM)
End If
IsInstalled = bSuccess
End Function
'=======================================================
' 函数名称:Install
' 函数说明:安装服务
'=======================================================
Public Function Install() As Boolean
Dim bSuccess As Boolean
Dim hSCM As Long, hService As Long
Dim szFilePath As String 'UNICODE编码
If IsInstalled() Then
bSuccess = True
Else
hSCM = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
If hSCM <> 0 Then
szFilePath = StrConv(App.Path & "\" & App.EXEName & ".EXE", vbUnicode)
hService = CreateService(hSCM, m_szServiceName, m_szDisplayName, _
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, _
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, _
szFilePath, vbNullString, ByVal 0&, vbNullString, vbNullString, vbNullString)
If hService <> 0 Then
bSuccess = True
Call CloseServiceHandle(hService)
End If
Call CloseServiceHandle(hService)
End If
End If
Install = bSuccess
End Function
'=======================================================
' 函数名称:Uninstall
' 函数说明:卸载服务
'=======================================================
Public Function Uninstall() As Boolean
Dim bSuccess As Boolean
Dim hSCM As Long, hService As Long
If Not IsInstalled Then
bSuccess = True
Else
hSCM = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_ALL_ACCESS)
If hSCM <> 0 Then
hService = OpenService(hSCM, m_szServiceName, SERVICE_STOP Or Delete)
If hService <> 0 Then
Dim status As SERVICE_STATUS
Call ControlService(hService, SERVICE_CONTROL_STOP, status)
bSuccess = DeleteService(hService)
Call CloseServiceHandle(hService)
End If
Call CloseServiceHandle(hSCM)
End If
End If
Uninstall = bSuccess
End Function
'=======================================================
' 函数名称:ServiceMain
' 函数说明:服务入口线程
'=======================================================
Public Sub ServiceMain(ByVal dwArgc As Long, ByVal lpszArgv As Long)
Dim hr As Long
Dim uMsg As MSG
Dim lStartTime As Long
'获得服务线程句柄
m_hServiceThread = GetCurrentThread()
'获得服务线程ID
m_dwServiceThreadId = GetCurrentThreadId()
'向SCM注册SCP回调函数地址
m_hServiceStatus = RegisterServiceCtrlHandler(StrPtr(m_szServiceName), AddressOf Handler)
'通知SCM服务正在启动
SendStatusToSCM SERVICE_START_PENDING
'初始化COM,让线程进入公寓线程模式
hr = CoInitialize(ByVal 0&)
'通知SCM服务已经运行
SendStatusToSCM SERVICE_RUNNING
'进入服务消息循环
lStartTime = GetTickCount()
Do While True
Call PeekMessage(uMsg, 0, 0, 0, PM_REMOVE)
If uMsg.message = WM_QUIT Then Exit Do
DispatchMessage uMsg
If GetTickCount() - lStartTime > 1000 Then
lStartTime = GetTickCount
MessageBeep -1
End If
Sleep 1
Loop
'取消公寓线程模式
Call CoUninitialize
'通知SCM服务已经停止
SendStatusToSCM SERVICE_STOPPED
'通知主线程结束消息循环
PostThreadMessage m_dwMainThreadId, WM_QUIT, 0, 0
End Sub
'=======================================================
' 函数名称:Handler
' 函数说明:接收并处理SCP控制消息
'=======================================================
Public Sub Handler(ByVal dwOpcode As Long)
Select Case dwOpcode
Case SERVICE_CONTROL_STOP '当接收到SCP发出的停止控制时
'通知SCM服务即将停止
SendStatusToSCM SERVICE_STOP_PENDING
'通知服务线程结束消息循环
Call PostThreadMessage(m_dwServiceThreadId, WM_QUIT, 0, 0)
Case SERVICE_CONTROL_PAUSE
Case SERVICE_CONTROL_CONTINUE
Case SERVICE_CONTROL_INTERROGATE
Case SERVICE_CONTROL_SHUTDOWN '当接收到SCP发出的关机控制时
'通知SCM服务即将停止
SendStatusToSCM SERVICE_STOP_PENDING
'通知服务线程结束消息循环
Call PostThreadMessage(m_dwServiceThreadId, WM_QUIT, 0, 0)
Case Else
End Select
End Sub
'=======================================================
' 函数名称:SendStatusToSCM
' 函数说明:服务状态设置辅助函数
'=======================================================
Public Function SendStatusToSCM(Optional ByVal dwCurrentState As SERVICE_STATE = 0) As Long
Dim status As SERVICE_STATUS
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS
If dwCurrentState <> 0 Then
status.dwCurrentState = dwCurrentState
End If
If dwCurrentState = SERVICE_START_PENDING Then
status.dwControlsAccepted = 0
Else
status.dwControlsAccepted = SERVICE_ACCEPT_STOP Or _
SERVICE_ACCEPT_SHUTDOWN '此处决定接收SCP的哪些控制消息
End If
SendStatusToSCM = SetServiceStatus(m_hServiceStatus, status)
End Function
'=======================================================
' 函数名称:GetFuncAddr
' 函数说明:获得函数指针辅助函数
'=======================================================
Public Function GetFuncAddr(ByVal lFuncAddr As Long) As Long
GetFuncAddr = lFuncAddr
End Function