VB同一个程序,多次启动,怎么才能知道某次启动的进程唯一性
用PID的话,也许关掉进程后,再次启动该进程PID可能会一样(虽然这种可能性非常小)
怎样才能知道某个进程的唯一性呢,即使进程名相同,PID相同,我也知道进程是我那次启动的
再加上进程的启动时间,应该唯一了。
新建一个clsMutex的类模块
Visual Basic code?Option Explicit Private Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName As String) As LongPrivate Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Type SECURITY_ATTRIBUTES nLength As Long lpSecurityDescriptor As Long bInheritHandle As LongEnd Type Private Const ERROR_ALREADY_EXISTS = 183& Private m_hMutex As Long Public Function CheckMutex(MutexName As String) As Boolean Dim s As SECURITY_ATTRIBUTES m_hMutex = CreateMutex(s, 0, MutexName) If Err.LastDllError = ERROR_ALREADY_EXISTS Then CheckMutex = False Else CheckMutex = True End If End Function Private Sub Class_Terminate() CloseHandle m_hMutex End Sub
然后在主框体引用下就可以保持软件启动的唯一性。。不知道你是不是这个需求。。
'单一实例
Visual Basic code?Private mut As clsMutex Private Sub Form_Load() '保持单一实例 Set mut = New clsMutex If Not mut.CheckMutex("an unique string") Then EndEnd Sub