vb创建NT服务

vb创建NT服务,第1张

概述'* ************************************************************** *    '*    程序名称:modNtSrv    '*    程序功能:实现NT服务    '*    作者:lyserver    '*    联系方式:http://blog.csdn.net/lyserver    '* ***************** '* ************************************************************** * '* 程序名称: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 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 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,"提示" Else MsgBox vbCrLf & "服务卸载失败!" & vbCrLf,"提示" 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) 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,SC_MANAGER_ALL_ACCESS) If hSCM <> 0 Then szfilePath = StrConv(App.Path & "\" & App.EXEname & ".EXE",vbUnicode) hService = CreateService(hSCM,m_szdisplayname,_ SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,_ SERVICE_DEMAND_START,SERVICE_ERROR_norMAL,_ szfilePath,ByVal 0&,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,SC_MANAGER_ALL_ACCESS) If hSCM <> 0 Then hService = OpenService(hSCM,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,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 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,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,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 总结

以上是内存溢出为你收集整理的vb创建NT服务全部内容,希望文章能够帮你解决vb创建NT服务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1281527.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存