您的位置:网站首页 > CAD新闻

判断CAD是否在运行

时间:2011-01-02 17:41:02 来源:未知

Private Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function EnumProcessModules Lib "psapi.dll" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Private Declare Function GetModuleFileNameExA Lib "psapi.dll" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const TH32CS_SNAPHEAPLIST = &H1
Private Const TH32CS_SNAPPROCESS = &H2
Private Const TH32CS_SNAPTHREAD = &H4
Private Const TH32CS_SNAPMODULE = &H8
Private Const TH32CS_SNAPALL = TH32CS_SNAPPROCESS + TH32CS_SNAPHEAPLIST + TH32CS_SNAPTHREAD + TH32CS_SNAPMODULE

Private Const PROCESS_TERMINATE = 1
Private Const PROCESS_QUERY_INFORMATION = 1024
Private Const PROCESS_VM_READ = 16
Private Const PROCESS_ALL_ACCESS = &H1F0FFF
Private Const MAX_PATH = 260

Private Type PROCESSENTRY32
    dwsize As Long
    cntusage As Long
    th32ProcessID As Long
    th32DefaultHeapID As Long
    th32ModuleID As Long
    cntThreads As Long
    th32ParentProcessID As Long
    pcPriClassBase As Long
    dwFlags As Long
    szExeFile As String * MAX_PATH
End Type

Public Function IsProcessRun(exeName As String) As Boolean
    Dim snap As Long, ret As Long, lProcess As Long
    Dim proc As PROCESSENTRY32
    Dim mName As String * MAX_PATH, modName As String

    snap = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0)
    proc.dwsize = Len(proc)
    ret = ProcessFirst(snap, proc)

    Do While ret <> 0
        mName = ""
        Dim Modules(1 To MAX_PATH) As Long, cbMNeeded As Long
        lProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, True, proc.th32ProcessID)
        If lProcess <> 0 Then
            ret = EnumProcessModules(lProcess, Modules(1), MAX_PATH, cbMNeeded)
            If ret <> 0 Then ret = GetModuleFileNameExA(lProcess, Modules(1), mName, Len(mName))
            modName = Trim(Left(mName, ret))
            If InStr(LCase(modName), LCase(exeName)) Then
                CloseHandle snap
                IsProcessRun = True
                Exit Function
            End If
        End If#p#分页标题#e#
        ret = ProcessNext(snap, proc)
    Loop
    CloseHandle snap
    IsProcessRun = False
End Function

使用的时候:Dim temp As Boolean
                     temp = IsProcessRun("ACAD.exe")