方法一:利用PrevInstance属性
If App.PrevInstance Then
Call MsgBox("对不起本程序已在运行中, 不得重复加载!!", vbCritical)
End
End If
优点:简单方便、
缺点:针对性不强、随意复制一份即可再次运行、
方法二:创建互斥体(个人比较喜欢)
Private Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Dim ret As Long
Private Sub Form_Load()
ret = CreateMutex(ByVal 0, 1, "FORM1") '这里改成程序的标题
If Err.LastDllError = 183 Then
ReleaseMutex ret
CloseHandle ret
MsgBox "程序只能运行一次!", vbCritical, ""
End
End If
End Sub
优点:只要窗体的标题不变,无论如何无法双开
缺点:和优点一样、只要其他程序历遍得到本窗体的句柄、然后sendmessage让窗体的标题(caption)改变就可以多开
方法三:全局原子、(02.09补上代码)
Private Declare Function GlobalAddAtom% Lib "kernel32" Alias "GlobalAddAtomA" (ByVal AtomName As String)
Private Declare Function GlobalFindAtom% Lib "kernel32" Alias "GlobalFindAtomA" (ByVal AtomName As String)
Private Declare Function GlobalDeleteAtom% Lib "kernel32" (ByVal AtomName As Integer)
Private Atom As Long
Private Sub IsAtom()
If GlobalFindAtom(App.EXEName) = 0 Then Atom = GlobalAddAtom(App.EXEName) Else unlaod Me
End Sub
Private Sub Form_Load()
IsAtom
End Sub
Private Sub Form_Unload(Cancel As Integer)
GlobalDeleteAtom Atom
End Sub
优点显而易见、非常规手段绝对不可能达到多开的目的、缺点么、、一旦程序被强制或非常规手段结束、就无法再次运行、原因很简单、当程序运行时会创建全局原子、一般情况下在程序退出时(unload事件)会删除全局原子、而强制结束程序则造成无法删除全局原子、所以就造成了无法打开的情况、、如果对这个情况你有好的解决方法、希望得到你的帮助、、