| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2131 人关注过本帖, 2 人收藏
标题:分享几个常用的模块
只看楼主 加入收藏
jiashie
Rank: 8Rank: 8
等 级:贵宾
威 望:10
帖 子:237
专家分:999
注 册:2009-4-30
结帖率:100%
收藏(2)
已结贴  问题点数:20 回复次数:7 
分享几个常用的模块
程序代码:
'//! Module Name:mduBrowseForFolder.bas
'//! Intro: 调用浏览文件夹对话框

Option Explicit

Private Type BROWSEINFO

    hOwner   As Long
    pidlRoot   As Long
    pszDisplayName   As String
    lpszTitle   As String
    ulFlags   As Long
    lpfn   As Long
    lParam   As Long
    iImage   As Long

End Type

Private Declare Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal pv As Long)
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
'Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Any) As Long
Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal dwLength As Long)
'Private Declare Function SHSimpleIDListFromPath Lib "shell32" Alias "#162" (ByVal szPath As String) As Long
Private Declare Function LocalAlloc Lib "kernel32" (ByVal uFlags As Long, ByVal uBytes As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function lstrcpyA Lib "kernel32" (lpString1 As Any, lpString2 As Any) As Long
Private Declare Function lstrlenA Lib "kernel32" (lpString As Any) As Long

Private Const MAX_PATH = 260

Private Const BFFM_INITIALIZED = 1
Private Const WM_USER = &H400
'Private Const BFFM_SETSTATUSTEXTA   As Long = (WM_USER + 100)
'Private Const BFFM_SETSTATUSTEXTW   As Long = (WM_USER + 104)
'Private Const BFFM_ENABLEOK         As Long = (WM_USER + 101)
Private Const BFFM_SETSELECTIONA As Long = (WM_USER + 102)
'Private Const BFFM_SETSELECTIONW    As Long = (WM_USER + 103)

Private Const LMEM_FIXED = &H0
Private Const LMEM_ZEROINIT = &H40
Private Const lPtr = (LMEM_FIXED Or LMEM_ZEROINIT)

Private Const BIF_RETURNONLYFSDIRS = 1
Private Const BIF_USENEWUI = &H40
'Private Const BIF_STATUSTEXT = &H4
Private Const BIF_EDITBOX = &H10

'-------------------------------------------
' 目录选择窗(允许指定初始目录、新建文件夹)
'-------------------------------------------
Public Function BrowseForFolder(Optional ByVal hWndOwner As Long, Optional ByVal sTitle As String = "请选择文件夹:", Optional ByVal sSelPath As String = "c:\", Optional NewFolder As Boolean = False) As String

    Dim BI        As BROWSEINFO
    Dim pidl      As Long
    Dim lpSelPath As Long
    Dim sPath     As String * MAX_PATH

    If Len(sSelPath) > 0 Then sSelPath = Replace(sSelPath & "\", "\\", "\")

    With BI
        .hOwner = hWndOwner
        .pidlRoot = 0
        .lpszTitle = sTitle
        .lpfn = FARPROC(AddressOf BrowseCallbackProcStr)
    
        lpSelPath = LocalAlloc(lPtr, Len(sSelPath))
        MoveMemory ByVal lpSelPath, ByVal sSelPath, Len(sSelPath)
    
        .lParam = lpSelPath
        .ulFlags = IIf(NewFolder, BIF_USENEWUI, BIF_RETURNONLYFSDIRS) Or BIF_EDITBOX

    End With

    pidl = SHBrowseForFolder(BI)

    If pidl Then
        If SHGetPathFromIDList(pidl, sPath) Then
            BrowseForFolder = Left$(sPath, InStr(sPath, vbNullChar) - 1)
        End If

        Call CoTaskMemFree(pidl)
    End If

    Call LocalFree(lpSelPath)

    'If   cancel   was   pressed,   sPath   =   ""
    If Len(BrowseForFolder) > 0 Then
        BrowseForFolder = Replace(BrowseForFolder & "\", "\\", "\")
    End If

End Function

Private Function BrowseCallbackProcStr(ByVal hwnd As Long, ByVal uMsg As Long, ByVal lParam As Long, ByVal lpData As Long) As Long

    Select Case uMsg

        Case BFFM_INITIALIZED
            Call SendMessage(hwnd, BFFM_SETSELECTIONA, 1, ByVal StrFromPtrA(lpData))

            'Call PostMessage(hwnd, BFFM_SETSELECTIONA, 1, ByVal StrFromPtrA(lpData))
        Case Else
    End Select

End Function

Private Function FARPROC(ByVal pfn As Long) As Long

    FARPROC = pfn
    
End Function

Private Function StrFromPtrA(ByVal lpszA As Long) As String

    Dim sRtn As String
    sRtn = String$(lstrlenA(ByVal lpszA), 0)
    Call lstrcpyA(ByVal sRtn, ByVal lpszA)
    StrFromPtrA = sRtn

End Function

程序代码:
'//! Module Name:mduIni.bas
'//! Intro:读写INI文件
Option Explicit

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Public Function GetValue(ByVal strIniFile As String, ByVal strSec As String, ByVal strItem As String, Optional ByVal strDef As String = "defaultValue") As String

    On Error GoTo errHandler

    Dim lRet    As Long
    Dim strTemp As String
    strTemp = String$(254, Chr$(0))
    lRet = GetPrivateProfileString(strSec, strItem, strDef, strTemp, 254, strIniFile)
    
    GetValue = Trim$(Left$(strTemp, lRet))
    
    If GetValue = "" Then GetValue = strDef
    
    Exit Function

errHandler:
    Debug.Print Err.Number
    GetValue = strDef
End Function

Public Function SetValue(ByVal strIniFile As String, ByVal strSec As String, ByVal strItem As String, ByVal strValue As String) As Long

    On Error Resume Next

    Dim lRet As Long
    lRet = WritePrivateProfileString(strSec, strItem, strValue, strIniFile)
    SetValue = IIf(lRet = 0, -1, 0)
End Function

程序代码:
'//! Module Name:mduOpenDialog.bas
'//! Intro:调用 打开和另存为对话框
Option Explicit
Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
Private Declare Function GetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (pOpenfilename As OPENFILENAME) As Long

Private Const OFN_PATHMUSTEXIST = &H800     '路径必须存在
Private Const OFN_FILEMUSTEXIST = &H1000    '文件必须存在
Private Const OFN_OVERWRITEPROMPT = &H2     '同名文件时提示

'' OPENFILENAME 结构的元素顺序必须按vb6自带的api浏览器里的格式声明。按foxApi V1.5里的声明时出错
Private Type OPENFILENAME

    lStructSize     As Long
    hwndOwner       As Long
    hInstance       As Long
    lpstrFilter     As String
    lpstrCustomFilter As String
    nMaxCustFilter  As Long
    nFilterIndex    As Long
    lpstrFile       As String
    nMaxFile        As Long
    lpstrFileTitle  As String
    nMaxFileTitle   As Long
    lpstrInitialDir As String
    lpstrTitle      As String
    flags           As Long
    nFileOffset     As Integer
    nFileExtension  As Integer
    lpstrDefExt     As String
    lCustData       As Long
    lpfnHook        As Long
    lpTemplateName  As String

End Type

Public Function ShowOpen(ByVal hwndOwner As Long, Optional ByVal strTitle As String = "打开...", Optional ByVal lpstrFilter As String = "All Files(*.*)" & vbNullChar & "*.*" & vbNullChar, Optional ByVal initDir As String = "c:\", Optional ByVal defExt As String = "*.JTF") As String

    On Error Resume Next

    Dim OFName As OPENFILENAME
    OFName.lStructSize = Len(OFName)
    OFName.hwndOwner = hwndOwner
    OFName.lpstrFilter = lpstrFilter
    OFName.lpstrFile = Space$(254)
    OFName.nMaxFile = 255
    OFName.lpstrFileTitle = Space$(254)
    OFName.nMaxFileTitle = 255
    OFName.lpstrInitialDir = initDir
    OFName.lpstrTitle = strTitle
    OFName.lpstrDefExt = defExt
    OFName.flags = OFN_FILEMUSTEXIST Or OFN_PATHMUSTEXIST

    'Debug.Print OFName.nFileExtension
    If GetOpenFileName(OFName) Then

        ShowOpen = Trim$(OFName.lpstrFile)

    Else

        ShowOpen = ""

    End If

End Function

Public Function ShowSave(ByVal hwndOwner As Long, Optional ByVal strTitle As String = "保存为...", Optional ByVal lpstrFilter As String = "All Files(*.*)" & vbNullChar & "*.*" & vbNullChar, Optional ByVal initDir As String = "c:\", Optional ByVal defExt As String = "*.XMC") As String

    On Error Resume Next
    
    Dim OFName As OPENFILENAME
    OFName.lStructSize = Len(OFName)
    OFName.hwndOwner = hwndOwner
    OFName.hInstance = App.hInstance
    OFName.lpstrFilter = lpstrFilter
    OFName.lpstrFile = Space$(254)
    OFName.nMaxFile = 255
    OFName.lpstrFileTitle = Space$(254)
    OFName.nMaxFileTitle = 255
    OFName.lpstrInitialDir = initDir
    OFName.lpstrTitle = strTitle
    OFName.flags = OFN_OVERWRITEPROMPT
    OFName.lpstrDefExt = defExt
    
    If GetSaveFileName(OFName) Then

        ShowSave = Trim$(OFName.lpstrFile)

    Else

        ShowSave = ""

    End If

End Function
收到的鲜花
  • Artless2010-05-13 01:25 送鲜花  10朵   附言:好文章
搜索更多相关主题的帖子: 模块 分享 
2010-05-12 17:00
jiashie
Rank: 8Rank: 8
等 级:贵宾
威 望:10
帖 子:237
专家分:999
注 册:2009-4-30
收藏
得分:0 
程序代码:
'//! Module Name:mnuInet.bas
'//! Intro:根据域名获取IP(域名解析)、根据IP获取域名
Option Explicit

Private Const WS_VERSION_REQD = &H101
Private Const WS_VERSION_MAJOR = WS_VERSION_REQD \ &H100 And &HFF&
Private Const WS_VERSION_MINOR = WS_VERSION_REQD And &HFF&
Private Const MIN_SOCKETS_REQD = 1
Private Const SOCKET_ERROR = -1
Private Const WSADescription_Len = 256
Private Const WSASYS_Status_Len = 128

Private Type HOSTENT

    hname       As Long
    hAliases    As Long
    hAddrType   As Integer
    hLength     As Integer
    hAddrList   As Long

End Type
    
Private Type WSADATA

    wVersion        As Integer
    wHighVersion    As Integer
    szDescription(0 To WSADescription_Len)       As Byte
    szSystemStatus(0 To WSASYS_Status_Len)       As Byte
    iMaxSockets     As Integer
    iMaxUdpDg       As Integer
    lpszVendorInfo  As Long

End Type

Private Declare Function gethostbyaddr Lib "WSOCK32.DLL" (addr As Any, ByVal byteslen As Integer, addrtype As Integer) As Long
Private Declare Function gethostbyname Lib "WSOCK32.DLL" (ByVal hostname$) As Long
Private Declare Function WSAGetLastError Lib "WSOCK32.DLL" () As Long
Private Declare Function WSAStartup Lib "WSOCK32.DLL" (ByVal wVersionRequired&, lpWSAData As WSADATA) As Long
Private Declare Function WSACleanup Lib "WSOCK32.DLL" () As Long
Private Declare Sub RtlMoveMemory Lib "KERNEL32" (hpvDest As Any, ByVal hpvSource&, ByVal cbCopy&)

Private Const ERROR_USER As Long = 531

Private Function HiByte(ByVal wParam As Integer) As Integer                  '获得整数的高位
    HiByte = wParam \ &H100 And &HFF&
End Function
    
Private Function LoByte(ByVal wParam As Integer) As Integer                  '获得整数的低位
    LoByte = wParam And &HFF&
End Function
    
Private Function SocketsInit() As Long
On Error GoTo errHandler

    Dim WSAD      As WSADATA
    Dim iReturn   As Integer
    Dim sLowByte  As String
    Dim sHighByte As String
    Dim sMsg      As String
          
    iReturn = WSAStartup(WS_VERSION_REQD, WSAD)
          
    If iReturn <> 0 Then
        Err.Raise ERROR_USER, , "Winsock.dll 没有反应."
    End If
          
    If LoByte(WSAD.wVersion) < WS_VERSION_MAJOR Or (LoByte(WSAD.wVersion) = WS_VERSION_MAJOR And HiByte(WSAD.wVersion) < WS_VERSION_MINOR) Then
        sHighByte = Trim$(Str$(HiByte(WSAD.wVersion)))
        sLowByte = Trim$(Str$(LoByte(WSAD.wVersion)))
        sMsg = "Windows Sockets版本 " & sLowByte & "." & sHighByte
        sMsg = sMsg & " 不被winsock.dll支持   "
        
        Err.Raise ERROR_USER, , sMsg

    End If
          
    If WSAD.iMaxSockets < MIN_SOCKETS_REQD Then
        sMsg = "这个系统需要的最少Sockets数为   "
        sMsg = sMsg & Trim$(Str$(MIN_SOCKETS_REQD))
        Err.Raise ERROR_USER, , sMsg
    End If
    
    SocketsInit = 0
    Exit Function
errHandler:
    Debug.Print Err.Number, Err.Description
    SocketsInit = -1
End Function
    
Private Function SocketsCleanup() As Long

On Error GoTo errHandler

    Dim lReturn As Long
          
    lReturn = WSACleanup()
          
    If lReturn <> 0 Then
        Err.Raise ERROR_USER, , "Socket错误 " & Trim$(Str$(lReturn)) & " occurred in Cleanup"
    End If

    SocketsCleanup = 0
    Exit Function
errHandler:
    Debug.Print Err.Number, Err.Description
    SocketsCleanup = -1
End Function

Public Function GetIP(ByVal strName As String) As String

    On Error GoTo errHandler

    Dim hostent_addr      As Long
    Dim host              As HOSTENT
    Dim hostip_addr       As Long
    Dim temp_ip_address() As Byte
    Dim i                 As Integer
    Dim ip_address        As String
    
    If SocketsInit() = -1 Then
        Err.Raise ERROR_USER, , "Sockets初始化失败"
    End If
    
    hostent_addr = gethostbyname(strName)
          
    If hostent_addr = 0 Then
        Err.Raise ERROR_USER, , "主机名不能被解析"

    End If
    
    RtlMoveMemory host, hostent_addr, LenB(host)
    RtlMoveMemory hostip_addr, host.hAddrList, 4
          
    ReDim temp_ip_address(1 To host.hLength)
    RtlMoveMemory temp_ip_address(1), hostip_addr, host.hLength
          
    For i = 1 To host.hLength
        ip_address = ip_address & temp_ip_address(i) & "."
    Next

    ip_address = Mid$(ip_address, 1, Len(ip_address) - 1)
          
    GetIP = ip_address
    
    Call SocketsCleanup
    
    Exit Function

errHandler:
    Debug.Print Err.Number, Err.Description
    Call SocketsCleanup
    GetIP = ""
End Function

Private Function GetName(ByVal addrStr As String) As String

    On Error GoTo errHandler

    Dim hostent_addr   As Long
    Dim host           As HOSTENT
    Dim addr(0 To 50)  As Byte
    Dim addrs          As String
    Dim hname(1 To 50) As Byte
    Dim s              As String
    Dim i              As Integer
    Dim j              As Integer
    Dim temp_int       As Integer
    Dim byt            As Byte
    
    s = Trim$(addrStr)
    i = 0
    j = 0

    Do
        temp_int = 0
        i = i + 1

        Do While Mid$(s, i, 1) >= "0" And Mid$(s, i, 1) <= "9" And i <= Len(s)
            temp_int = temp_int * 10 + Mid$(s, i, 1)
            i = i + 1
        Loop

        If temp_int <= 255 Then
            addr(j) = temp_int
            j = j + 1
        End If
            
    Loop Until Mid$(s, i, 1) <> "." Or i > Len(s) Or temp_int > 255

    If temp_int > 255 Then
        Err.Raise ERROR_USER, , "地址非法"
    End If

    If SocketsInit() = -1 Then
        Err.Raise ERROR_USER, , "Sockets初始化失败"
    End If

    hostent_addr = gethostbyaddr(addr(0), j, 2)

    If hostent_addr = 0 Then
        Err.Raise ERROR_USER, , "此地址无法解析"
    End If

    RtlMoveMemory host, hostent_addr, LenB(host)
    RtlMoveMemory hname(1), host.hname, 50
    
    j = 51

    For i = 1 To 50

        If hname(i) = 0 Then
            j = i
        End If

        If i >= j Then
            hname(i) = 32
        End If

    Next i

    GetName = Trim$(StrConv(hname, vbUnicode))

    Call SocketsCleanup

    Exit Function

errHandler:
    Debug.Print Err.Number, Err.Description
    Call SocketsCleanup

    GetName = ""
End Function


程序代码:
'//! Module Name:mduAutoRun.bas
'//! Intro:设置或取消 随系统启动
Option Explicit

Public Function SetAutoRun(ByVal strName As String, ByVal strApp As String, ByVal isSetup As Boolean) As Long

    On Error GoTo errHandler

    Dim objShell As Object
    Set objShell = CreateObject("Wscript.Shell")

    If isSetup Then
        objShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\" & strName, Chr$(34) & strApp & Chr$(34)
    Else
        objShell.RegDelete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\" & strName
    End If

    Set objShell = Nothing

    SetAutoRun = 0

    Exit Function

errHandler:
    Debug.Print Err.Number, Err.Description
    #If DEBUG_MODE Then
        Stop: Resume
    #End If
    SetAutoRun = -1
End Function
2010-05-12 17:08
jiashie
Rank: 8Rank: 8
等 级:贵宾
威 望:10
帖 子:237
专家分:999
注 册:2009-4-30
收藏
得分:0 
程序代码:
'//! ClassName:clsSrvCtrl.cls
'//! Intro:安装/卸载/启动/暂停/停止系统服务
'//! 其实更好用的是微软官方的NTSVC.ocx

'Dim NTSrv As New clsSrvCtrl
'
'With NTSrv
'    .Name = "00000000007server"
'    .Account = "LocalSystem"
'    .Description = "00000000007server"
'    .DisplayName = "00000000007server"
'    .Command = "c:\3.exe"
'    .Interact = SERVICE_INTERACT_WITH_DESKTOP
'    .StartType = SERVICE_DEMAND_START
'End With
'
'Call NTSrv.SetNTService
'
'安装服务
'SetNTService()
'开始服务
'StartNTService()
'停止服务
'StopNTService()
'卸载服务
'DeleteNTService()
'检测服务是否安装
'GetServiceConfig()
'当前服务状态
'GetServiceStatus

Option Explicit

Private Const SERVICE_WIN32_OWN_PROCESS = &H10&
Private Const SERVICE_INTERACTIVE_PROCESS = &H100&
Private Const SERVICE_CONFIG_DESCRIPTION = 1&
Private Const ERROR_SERVICE_DOES_NOT_EXIST = 1060&
Private Const SC_MANAGER_CONNECT = &H1&
Private Const SC_MANAGER_CREATE_SERVICE = &H2&
Private Const STANDARD_RIGHTS_REQUIRED = &HF0000
Private Const SERVICE_QUERY_CONFIG = &H1&
Private Const SERVICE_CHANGE_CONFIG = &H2&
Private Const SERVICE_QUERY_STATUS = &H4&
Private Const SERVICE_ENUMERATE_DEPENDENTS = &H8&
Private Const SERVICE_START = &H10&
Private Const SERVICE_STOP = &H20&
Private Const SERVICE_PAUSE_CONTINUE = &H40&
Private Const SERVICE_INTERROGATE = &H80&
Private Const SERVICE_USER_DEFINED_CONTROL = &H100&
Private 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 Enum SERVICE_START_TYPE

    SERVICE_AUTO_START = 2&
    SERVICE_DEMAND_START = 3&
    SERVICE_DISABLED = &H4

End Enum

Public Enum SERVICE_INTERACT_TYPE

    SERVICE_INTERACT_WITHNOT_DESKTOP = &H10&
    SERVICE_INTERACT_WITH_DESKTOP = &H10& Or &H100&

End Enum

Private Const SERVICE_ERROR_NORMAL As Long = 1
Private Const ERROR_INSUFFICIENT_BUFFER = 122&

Private 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

End Enum

Private 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

Private Type QUERY_SERVICE_CONFIG

    dwServiceType As Long
    dwStartType As Long
    dwErrorControl As Long
    lpBinaryPathName As Long
    lpLoadOrderGroup As Long
    dwTagId As Long
    lpDependencies As Long
    lpServiceStartName As Long
    lpDisplayName As Long

End Type

Private Declare Function OpenSCManager Lib "advapi32" Alias "OpenSCManagerW" (ByVal lpMachineName As Long, ByVal lpDatabaseName As Long, ByVal dwDesiredAccess As Long) As Long
Private Declare Function CreateService Lib "advapi32" Alias "CreateServiceW" (ByVal hSCManager As Long, ByVal lpServiceName As Long, ByVal lpDisplayName As Long, ByVal dwDesiredAccess As Long, ByVal dwServiceType As Long, ByVal dwStartType As Long, ByVal dwErrorControl As Long, ByVal lpBinaryPathName As Long, ByVal lpLoadOrderGroup As Long, ByVal lpdwTagId As Long, ByVal lpDependencies As Long, ByVal lpServiceStartName As Long, ByVal lpPassword As Long) As Long
Private Declare Function DeleteService Lib "advapi32" (ByVal hService As Long) As Long
Private Declare Function CloseServiceHandle Lib "advapi32" (ByVal hSCObject As Long) As Long
Private Declare Function OpenService Lib "advapi32" Alias "OpenServiceW" (ByVal hSCManager As Long, ByVal lpServiceName As Long, ByVal dwDesiredAccess As Long) As Long   '** Change Service_Name as needed
Private Declare Function QueryServiceConfig Lib "advapi32" Alias "QueryServiceConfigW" (ByVal hService As Long, lpServiceConfig As QUERY_SERVICE_CONFIG, ByVal cbBufSize As Long, pcbBytesNeeded As Long) As Long
Private Declare Function QueryServiceStatus Lib "advapi32" (ByVal hService As Long, lpServiceStatus As SERVICE_STATUS) As Long
Private Declare Function ControlService Lib "advapi32" (ByVal hService As Long, ByVal dwControl As SERVICE_CONTROL, lpServiceStatus As SERVICE_STATUS) As Long
Private Declare Function StartService Lib "advapi32" Alias "StartServiceW" (ByVal hService As Long, ByVal dwNumServiceArgs As Long, ByVal lpServiceArgVectors As Long) As Long
Private Declare Function ChangeServiceConfig2 Lib "advapi32" Alias "ChangeServiceConfig2W" (ByVal hService As Long, ByVal dwInfoLevel As Long, lpInfo As Any) As Long
Private Declare Function NetWkstaUserGetInfo Lib "Netapi32" (ByVal reserved As Any, ByVal Level As Long, lpBuffer As Any) As Long
Private Declare Function NetApiBufferFree Lib "Netapi32" (ByVal lpBuffer As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function lstrcpyW Lib "kernel32" (ByVal lpString1 As Any, ByVal lpString2 As Any) As Long
Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long

Private Service_Name         As String
Private Service_Display_Name As String
Private Service_File_Path    As String
Private Service_Description  As String
Private Service_Account      As String
Private Service_Password     As String
Private Service_Type         As Long
Private Service_Interact     As Long

'查询服务运行状态,4运行,1停止
Public Function GetServiceStatus() As SERVICE_STATE
    Dim hSCManager As Long, hService As Long, Status As SERVICE_STATUS
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CONNECT)

    If hSCManager Then
        hService = OpenService(hSCManager, StrPtr(Service_Name), SERVICE_QUERY_STATUS)

        If hService Then
            If QueryServiceStatus(hService, Status) Then
                GetServiceStatus = Status.dwCurrentState
            End If

            CloseServiceHandle hService
        End If

        CloseServiceHandle hSCManager
    End If

End Function

'检测服务是否安装,返回0则安装
Public Function GetServiceConfig() As Long
    Dim hSCManager As Long, hService As Long
    Dim r          As Long, SCfg() As QUERY_SERVICE_CONFIG, r1 As Long, s As String
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CONNECT)

    If hSCManager Then
        hService = OpenService(hSCManager, StrPtr(Service_Name), SERVICE_QUERY_CONFIG)

        If hService Then
            ReDim SCfg(1 To 1)

            If QueryServiceConfig(hService, SCfg(1), 36, r) = 0 Then
                If Err.LastDllError = ERROR_INSUFFICIENT_BUFFER Then
                    r1 = r \ 36 + 1
                    ReDim SCfg(1 To r1)

                    If QueryServiceConfig(hService, SCfg(1), r1 * 36, r) Then
                        s = Space$(lstrlenW(SCfg(1).lpServiceStartName))
                        lstrcpyW StrPtr(s), SCfg(1).lpServiceStartName
                        Service_Account = s
                    Else
                        GetServiceConfig = Err.LastDllError
                    End If

                Else
                    GetServiceConfig = Err.LastDllError
                End If
            End If

            CloseServiceHandle hService
        Else
            GetServiceConfig = Err.LastDllError
        End If

        CloseServiceHandle hSCManager
    Else
        GetServiceConfig = Err.LastDllError
    End If

End Function

'安装服务
Public Function SetNTService() As Long
    Dim hSCManager As Long
    Dim hService   As Long, DomainName As String

    If Service_Account = "" Then Service_Account = "LocalSystem"
    If Service_Account <> "LocalSystem" Then

        '向用户帐号添加域名信息
        If InStr(1, Service_Account, "\") = 0 Then

            DomainName = GetDomainName()

            If Len(DomainName) = 0& Then DomainName = "."
            Service_Account = DomainName & "\" & Service_Account
        End If
    End If
    
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CREATE_SERVICE)

    If hSCManager Then
        '安装服务为自启动
        hService = CreateService(hSCManager, StrPtr(Service_Name), _
           StrPtr(Service_Display_Name), SERVICE_ALL_ACCESS, _
           Service_Interact, _
           Service_Type, SERVICE_ERROR_NORMAL, _
           StrPtr(Service_File_Path), 0&, _
           0&, 0&, StrPtr(Service_Account), _
           StrPtr(Service_Password))
                       
        If hService Then

            '向服务添加描述
            On Error Resume Next

            ChangeServiceConfig2 hService, SERVICE_CONFIG_DESCRIPTION, StrPtr(Service_Description)

            On Error GoTo 0

            CloseServiceHandle hService
        Else
            SetNTService = Err.LastDllError
        End If

        CloseServiceHandle hSCManager
    Else
        SetNTService = Err.LastDllError
    End If
        
End Function

'卸载服务
Public Function DeleteNTService() As Long
    Dim hSCManager As Long
    Dim hService   As Long, Status As SERVICE_STATUS
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CONNECT)

    If hSCManager Then
        hService = OpenService(hSCManager, StrPtr(Service_Name), SERVICE_ALL_ACCESS)

        If hService Then
            '如果服务运行着则先停掉它
            ControlService hService, SERVICE_CONTROL_STOP, Status

            If DeleteService(hService) = 0 Then
                DeleteNTService = Err.LastDllError
            End If

            CloseServiceHandle hService
        Else
            DeleteNTService = Err.LastDllError
        End If

        CloseServiceHandle hSCManager
    Else
        DeleteNTService = Err.LastDllError
    End If

End Function

'本地域名称
Public Function GetDomainName() As String
    Dim lpBuffer As Long, l As Long, p As Long

    If NetWkstaUserGetInfo(0&, 1&, lpBuffer) = 0 Then
        CopyMemory p, ByVal lpBuffer + 4, 4
        l = lstrlenW(p)

        If l > 0 Then
            GetDomainName = Space$(l)
            CopyMemory ByVal StrPtr(GetDomainName), ByVal p, l * 2
        End If

        NetApiBufferFree lpBuffer
    End If

End Function

'开始服务
Public Function StartNTService() As Long
    Dim hSCManager As Long, hService As Long
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CONNECT)

    If hSCManager Then
        hService = OpenService(hSCManager, StrPtr(Service_Name), SERVICE_START)

        If hService Then
            If StartService(hService, 0, 0) = 0 Then
                StartNTService = Err.LastDllError
            End If

            CloseServiceHandle hService
        Else
            StartNTService = Err.LastDllError
        End If

        CloseServiceHandle hSCManager
    Else
        StartNTService = Err.LastDllError
    End If

End Function

'停止服务
Public Function StopNTService() As Long
    Dim hSCManager As Long, hService As Long, Status As SERVICE_STATUS
    hSCManager = OpenSCManager(0&, 0&, SC_MANAGER_CONNECT)

    If hSCManager Then
        hService = OpenService(hSCManager, StrPtr(Service_Name), SERVICE_STOP)

        If hService Then
            If ControlService(hService, SERVICE_CONTROL_STOP, Status) = 0 Then
                StopNTService = Err.LastDllError
            End If

            CloseServiceHandle hService
        Else
            StopNTService = Err.LastDllError
        End If

        CloseServiceHandle hSCManager
    Else
        StopNTService = Err.LastDllError
    End If

End Function

'服务名称
Public Property Let Name(ByVal sSrvName As String)
    Service_Name = sSrvName
End Property

'显示名称
Public Property Let DisplayName(ByVal sDisName As String)
    Service_Display_Name = sDisName
End Property

'服务描述
Public Property Let Description(ByVal sDes As String)
    Service_Description = sDes
End Property

'执行参数
Public Property Let Command(ByVal sSrvCmd As String)
    Service_File_Path = sSrvCmd
End Property

'启动账户
Public Property Let Account(ByVal sSrvAccount As String)

    If sSrvAccount <> "" Then Service_Account = sSrvAccount
End Property

'账户密码
Public Property Let Password(ByVal sSrvPassword As String)
    Service_Password = sSrvPassword
End Property

'启动类型
Public Property Let StartType(ByVal lType As SERVICE_START_TYPE)
    Service_Type = lType
End Property

'交互类型
Public Property Let Interact(ByVal lType As SERVICE_INTERACT_TYPE)
    Service_Interact = lType
End Property

Private Sub Class_Initialize()

    If Service_Account = "" Then Service_Account = "LocalSystem"
End Sub


[ 本帖最后由 jiashie 于 2010-5-12 17:13 编辑 ]
2010-05-12 17:11
bczgvip
Rank: 14Rank: 14Rank: 14Rank: 14
等 级:贵宾
威 望:66
帖 子:1310
专家分:5312
注 册:2009-2-26
收藏
得分:5 
感谢分享。
还有,可以把这些文件放在vb6安装目录下的Template文件夹里。
子文件夹有 Classes、Forms、Modules、Projects、Proppage、Userctls、Userdocs、Mdiforms。
2010-05-12 19:01
W11400661
Rank: 8Rank: 8
来 自:达拉达斯
等 级:蝙蝠侠
威 望:2
帖 子:163
专家分:834
注 册:2008-10-12
收藏
得分:5 
感谢分享!
2010-05-12 22:04
gyll
Rank: 2
等 级:论坛游民
帖 子:56
专家分:21
注 册:2009-4-22
收藏
得分:5 
学习

学习C
2010-05-12 23:41
Artless
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
等 级:贵宾
威 望:103
帖 子:4211
专家分:28888
注 册:2009-4-8
收藏
得分:5 
感谢分享

无知
2010-05-13 01:23
xakir
Rank: 1
等 级:新手上路
帖 子:22
专家分:0
注 册:2009-3-9
收藏
得分:0 
留个标记
2010-11-25 12:56
快速回复:分享几个常用的模块
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.077937 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved