在 VB 中如何实现如下功能:A程序是一个窗口程序,保证系统中任何时刻只能有一个
A程序!我单用 FindWindow 好像不行?哪位有简单的办法?
谢谢!

解决方案 »

  1.   

    Private Sub Form_Load()
        If App.PrevInstance Then End
    End Sub
      

  2.   

    App.PrevInstance 能实现你的功能吗?
      

  3.   

    自己的程序利用互斥体绝对行,App.PrevInstance还是有问题的,把哪个EXE文件考到另外一个路径下照样可以运行多个实例。
    启动项选为Sub Main
    别人的程序就有点难啊 ,FindWindow也不尝是个办法,但似乎苯了点。Public Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
    Public Type SECURITY_ATTRIBUTES
            nLength As Long
            lpSecurityDescriptor As Long
            bInheritHandle As Long
    End Type
    Public Const ERROR_ALREADY_EXISTS = 183&
    Private Sub Main()
        'KPD-Team 1999
        'URL: http://www.allapi.net/
        'E-Mail: [email protected]
        ' -> code by Raist Lin
        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
        Form1.Show
            'No other instance detected...
            'Your program-load code here
        End If
    End Sub
      

  4.   

    用Spy++得到窗体的类名之后也好办~比如资源管理器就是:
    FindWindow("ExploreWClass", vbNullString)可以忽略窗口标题
      

  5.   

    //转自CSDN上的《VB常见100问》。
    7.只容许运行一个程序实例(利用互斥体)选择启动对象为sub main()
    module:
    Public Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" _ (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName _
     As String) As Long
    Public Type SECURITY_ATTRIBUTES
            nLength As Long
            lpSecurityDescriptor As Long
            bInheritHandle As Long
    End Type
    Public Const ERROR_ALREADY_EXISTS = 183&
    Private Sub Main()
        Dim sa As SECURITY_ATTRIBUTES
        sa.bInheritHandle = 1
        sa.lpSecurityDescriptor = 0
        sa.nLength = Len(sa)
        Debug.Print CreateMutex(sa, 1, App.Title)  '这一行可千万不能删除啊
        Debug.Print Err.LastDllError
        If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then
            MsgBox "More than one instance"
        Else
            Form1.Show
        End If
    End Sub
      

  6.   

    多谢大家,我用的是:Private Sub Form_Load()
        
      dim FirstHwd as long
      dim RetHwd as long  FirstHwd=FindWindow(VBNullString,"XXX")
      RetHwd=FindWindowEx(0,FirstHwd,VBNullString,"XXX")  if RetHwd<>0 then
           End
      if end
    End sub
    End Sub