查看: 508  |  回复: 0
  VB6 本程序只运行一次,重复运行就提示并退出
楼主
发表于 2023年4月18日 18:33

先对代码生成exe文件,运行后再运行一下就看到效果了。

Private Declare Function CreateMutex Lib "kernel32" _
                Alias "CreateMutexA" _
                (lpMutexAttributes As SECURITY_ATTRIBUTES, _
                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 Long
                
Private Declare Function GetLastError Lib "kernel32" () As Long

Private Type SECURITY_ATTRIBUTES
        nLength As Long
        lpSecurityDescriptor As Long
        bInheritHandle As Long
End Type

Private Const ERROR_ALREADY_EXISTS = 183&

Private mlngHMutex As Long

Private Sub Form_Load()
    If IsPrevAppRunning = True Then
        MsgBox "This app is already running.", _
                vbOKOnly + vbExclamation, "App Already In Use"
        Unload Me
        Set frmMutex = Nothing
    End If
End Sub

Private Sub Form_Terminate()
    If mlngHMutex <> 0 Then
        'Close the mutex.
        ReleaseMutex mlngHMutex
        CloseHandle mlngHMutex
    End If
End Sub

Private Function IsPrevAppRunning() As Boolean
    On Error GoTo error_IsPrevAppRunning
    
    Dim lngVBRet As Long
    Dim sa As SECURITY_ATTRIBUTES
    mlngHMutex = CreateMutex(sa, True, "Test")
    lngVBRet = Err.LastDllError
    If lngVBRet = ERROR_ALREADY_EXISTS Then
    'This app is already running.
        IsPrevAppRunning = True
    End If
    Exit Function
    
error_IsPrevAppRunning:
    IsPrevAppRunning = False
End Function


1楼
发表于 2023年4月20日 00:56

也可以试试这个代码:

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


您需要登录后才可以回帖 登录 | 立即注册
【本版规则】请勿发表违反国家法律的内容,否则会被冻结账号和删贴。
用户名: 立即注册
密码:
2020-2024 MaNongKu.com