使用FindWindow函数,如下:
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpclassName As Long, ByVal lpwindowName As String) As Long
Dim hApp As Long
Dim Appname As String hpp = FindWindow(0, Appname) 其中,Appname为所要查找的应用程序的窗体的caption,hpp为long型,为函数的返回值,如果hpp 为非0,则,证明该应用程序已经运行。
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpclassName As Long, ByVal lpwindowName As String) As Long
Dim hApp As Long
Dim Appname As String hpp = FindWindow(0, Appname) 其中,Appname为所要查找的应用程序的窗体的caption,hpp为long型,为函数的返回值,如果hpp 为非0,则,证明该应用程序已经运行。
If App.PrevInstance Then
msg1 = "程序已运行,请检查是否最小化!"
MsgBox msg1, vbCritical
End
End If
End Sub
Private Sub Form_Load()
If App.PrevInstance Then '检视前一版本
MsgBox "此程式已经在执行中!", 48
End
End If
End Sub
1防止程序被重复运行 如果你不希望你的VB应用程序被别人通过多次双击图标而重复运行,导致内存不足或其它意外,你可以在程序中增加以下几行:
Private Sub Form_ Load
if app.previnstance then
msgbox ″程序正在运行,请检查窗口是否被最小化。″
end if
End Sub
你的程序可能只支持单一用户,那么怎么来避免多用户同时使用它吗?
你可以利用 App 对象的 PrevInstance 属性来轻易达到你的目的。
我们可以在程序打开时加入以下代码来验证:
If App.PrevInstance Then
MsgBox ("程序已经运行,不能再次装载。"), vbExclamation
Unload Me
End If在不同目录下
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
程序:
winHwnd = FindWindow(vbNullString, "程序名") If winHwnd = 0 Then '说明的程序在运行
end
end if
Public Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As LongSub Main()
Dim HndMod as long
HndMod=GetModuleHandle(app.exename)
if HndMod<>0 then
end
end if