只允许程序单实例运行

有时候,我们只能允许程序单实例运行,以免程序运行出错。可以通过使用App.PrevInstance和系统级的Mutex等多种办法来实现。

代码如下:

vbnet 复制代码
'用户昵称: 留下些什么
'个人简介: 一个会做软件的货代
'CSDN网址:https://blog.csdn.net/zezese
'电子邮箱:31319180@qq.com

Option Explicit

Private Declare Function CreateMutex Lib "kernel32.dll" Alias "CreateMutexA" (ByRef lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

Private Const ERROR_ALREADY_EXISTS As Long = 183&

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

Dim hAppMutex As Long


Private Sub Form_Initialize()

    '方法1: 使用 App.PrevInstance 这种办法,只要EXE文件改个名字就可以运行多个实例。
    
    If App.PrevInstance Then
        MsgBox "方法1: 使用 App.PrevInstance 这种办法,只要EXE文件改个名字就可以运行多个实例。"
        End
    End If


    '方法2: 使用系统级的Mutex,改名字也没有用。
    
    If IsRunning Then
    
        MsgBox "方法2: 使用系统级的Mutex,改名字也没有用。"
        
        End
    End If

End Sub


Private Function IsRunning() As Boolean

    Dim sa As SECURITY_ATTRIBUTES
    sa.bInheritHandle = 1
    sa.lpSecurityDescriptor = 0
    sa.nLength = Len(sa)
    
    hAppMutex = CreateMutex(sa, 1, "31319180@qq.com") ' 这里请使用自己的标志字符串或者 GUID 字符串
    
    If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then
        
       CloseHandle hAppMutex
       
       IsRunning = True
        
    End If

End Function


Private Sub Form_Terminate()
    CloseHandle hAppMutex
End Sub
相关推荐
caimouse22 分钟前
Reactos 第 7 章 视窗报文 — 7.7 鼠标器输入线程
windows
caimouse40 分钟前
Reactos 第 7 章 视窗报文 — 7.2 视窗报文的接收
windows
caimouse1 小时前
Reactos 第 8 章 结构化异常处理 — 8.3 用户空间的结构化异常处理
windows
caimouse1 小时前
Reactos 第 9 章 设备驱动 — 9.6 中断处理
网络·windows
caimouse1 小时前
Reactos 第 7 章 视窗报文 — 7.6 键盘输入线程
windows
yinhunzw2 小时前
Claude code windows 安装
windows
七仔啊2 小时前
windows server 2022 部署前后端项目
windows
caimouse3 小时前
Reactos 第 7 章 视窗报文 — 7.4 用户空间的外挂函数
windows
辣香牛肉面3 小时前
Windows发票工具大全
windows·发票助手
caimouse3 小时前
Reactos 第 9 章 设备驱动 — 9.3 DPC函数及其执行
windows