原代码如下:
strClassName = "datachange"
    m_hMutex = OpenMutex(MUTEX_ALL_ACCESS, False, strClassName)
    
    If m_hMutex = 0 Then
        m_hMutex = CreateMutex(0, True, strClassName)
         
    Else
        MsgBox "datachange 已经存在!", vbOKOnly
        End
    End If
当我第一个进程执行时,我通过createmutex创建一个strclassname,保证系统里面只有一个我写的该应用程序执行,但是,第一个进程没有关闭,第二个进程起来的时候,使用OPENMUTEX函数得到为0?
我该如何取到我通过createmutex创建的strclassname?
请指教!!

解决方案 »

  1.   

    为保证只有一个进程的话你用CREATEMUTEX就能判断了,因为第二次创建的话会返回失败代码的:ERROR_ALREADY_EXISTS。(假设你的程序退出的时候已经关闭互斥对象了,这是当然的事情了)
    当然你用OPEN来判断其存在性也可以但是不该用MUTEX_ALL_ACCESS而是该用SYNCHRONIZE
      

  2.   

    要保证只有1个实例在运行,你用App.PreInstance来判断不就可以了么?
      

  3.   

    可是我第二次创建的話同样可以创建出来呀!你凭什么以为自己创建成功了呢?
    你创建后检查err对象的DLLERROR看,返回的就是我说的那个错误码。
      

  4.   

    要保证只有1个实例在运行,并且想使用Mutex的话,只调用CreateMutex就可以了,参考下面:'This code must be pasted into a module
    'Set the project's startup object to 'Sub Main' (-> Project -> Project Properties -> General Tab -> Startup Object)
    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
            'No other instance detected...
            'Your program-load code here
        End If
    End Sub
      

  5.   

    另外,可以参考:
    http://www.zjol.com.cn/vbbible/software/program/vb/ccw/htmapi73.htm