只允许程序单实例运行

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

代码如下:

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

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, "[email protected]") ' 这里请使用自己的标志字符串或者 GUID 字符串
    
    If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then
        
       CloseHandle hAppMutex
       
       IsRunning = True
        
    End If

End Function


Private Sub Form_Terminate()
    CloseHandle hAppMutex
End Sub
相关推荐
donglxd39 分钟前
老电脑优化全知道(包括软件和硬件优化)
运维·windows·系统安全
ZXF-BW5 小时前
联想笔记本电脑在Windows下通过联想驱动实现风扇控制
windows·电脑·联想·风扇
csdn_aspnet7 小时前
如何在 Windows 10 中使用 WSL 和 Debian 安装 Postgresql 和 Postgis
windows·postgresql·debian
九鼎科技-Leo8 小时前
写windows服务日志-.net4.5.2-定时修改数据库中某些参数
数据库·windows·.net
扛枪的书生21 小时前
AD 侦查-MSRPC
windows·渗透·kali·提权·域渗透
程序员Bears1 天前
IntelliJ IDEA 2025系列通用软件安装教程(Windows版)
ide·windows·pycharm·webstorm
CHANG_THE_WORLD1 天前
Windows DirectWrite接口 遍历字体信息
windows
只可远观1 天前
Flutter Dart 集合类型List Set Map详解军 以及循环语句 forEaclh map where any every
windows·flutter·list
yangshuo12811 天前
风车邮箱系统详细使用指南:Windows与Ubuntu双平台解析
linux·windows·ubuntu
技术liul1 天前
如何在iStoreOS DHCP中排除特定IP地址
网络·windows·tcp/ip