各位老兄,如何让VB程序只有一个实例在运行,望大家指教,谢了!
解决方案 »
- VB中如何实现颜色选单的制作?
- 急,急,急!ACCESS中向有自动增长约束和主键约束的字段插入数据
- 复制文件
- 怎样捕捉commondialog对话框,并自动填入文件名?
- HELP!!!出现:"客户事件句柄调用了一个提供程序中的非重入方法"是怎么回事?
- 这个Systray代码的特性为何不像MSN MSG那样智能呢?
- 希望能和这里的朋友认识一下!
- 怎样loadpicture很大的图片文件,因为我使用这个函数时,会出现内存溢出
- 如何在菜单里实现打开一个网页的链接?50分相送!
- 两个仍然未解决的菜鸟问题!
- 散点分,省得都说偶一毛不拔。。。谢谢大家捧场。。。来VB做斑竹感到非常荣幸。。。
- 急!急!急!急!快考试了但是vb一点不会,有几个题目请专家给作一下,来者有分
If App.PrevInstance = True Then
MsgBox "您不能同时运行多个程序!"
Exit Sub
End If
end sub
private sub form1_load()
If App.PrevInstance = True Then End
end sub
End
End If
有用FindWindow这个API的
也有用CreateMutex这个API的很多实例
Private Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type
Private Const ERROR_ALREADY_EXISTS = 183&Private Sub Form_Load()
Dim sa As SECURITY_ATTRIBUTES
sa.bInheritHandle = 1
sa.lpSecurityDescriptor = 0
sa.nLength = Len(sa)
'Try to create a new Mutex
Debug.Print CreateMutex(sa, 1, App.Title)
Debug.Print Err.LastDllError
'Check if the function was succesfull
If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then
'More than one instance detected
MsgBox "More than one instance"
Else
'No other instance detected...
'Your program-load code here
End If
End Sub
End
End If
标准做法
end
end if
用App.PrevInstance并不能够非常可靠的保证只运行一次,把要执行的程序换个目录运行试试
看,是不是即使是使用了App.PrevInstance,程序还是可以跑起来?可靠的办法是使用系统互斥量:我的代码:(非常精简了,大家在工程中用得上)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 LongPrivate Sub Form_Load()
Dim ret As Long
ret = CreateMutex(ByVal 0, 1, "My_Project_Version 1.0")
If Err.LastDllError = 183 Then '应用程序已经运行了
ReleaseMutex ret
CloseHandle ret
End
End If
End Sub你可以根据你的应用更改值:"My_Project_Version 1.0"其实ret应该定义成全局变量,然后有必要再添加代码:Private Sub Form_Unload(Cancel As Integer)
If ret Then
ReleaseMutex ret
CloseHandle ret
End If
End Sub