各位老兄,如何让VB程序只有一个实例在运行,望大家指教,谢了!

解决方案 »

  1.   

    private sub form1_load()
        If App.PrevInstance = True Then
            MsgBox "您不能同时运行多个程序!"
            Exit Sub
        End If
    end sub
      

  2.   

    sub MAIN()
    private sub form1_load()
        If App.PrevInstance = True Then  End 
    end sub
      

  3.   

    If App.PrevInstance  Then
            End 
        End If
      

  4.   

    搜索一下吧有用PrevInstance 的
    有用FindWindow这个API的
    也有用CreateMutex这个API的很多实例
      

  5.   

    Option ExplicitPrivate Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
    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
      

  6.   

    If App.PrevInstance  Then
            End 
        End If
    标准做法
      

  7.   

    if app.previnstance=true then
            end
         end if
      

  8.   

    If App.PrevInstance = True Then  End 支持
      

  9.   


    用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