只允许程序单实例运行

有时候,我们只能允许程序单实例运行,以免程序运行出错。可以通过使用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
相关推荐
web150854159351 小时前
超级详细Spring AI运用Ollama大模型
人工智能·windows·spring
久绊A5 小时前
Python 基本语法的详细解释
开发语言·windows·python
菜鸟单飞16 小时前
介绍一款非常实用的PDF阅读软件!
windows·pdf·电脑
流星白龙20 小时前
【Linux】35.封装 UdpSocket(2)
linux·运维·windows
waicsdn_haha20 小时前
Visual Studio Code 2025 安装与高效配置教程
c语言·ide·windows·vscode·微软·编辑器·win7
ChoSeitaku1 天前
12.重复内容去重|添加日志|部署服务到Linux上(C++)
linux·c++·windows
Major_xx1 天前
装win10系统提示“windows无法安装到这个磁盘,选中的磁盘采用GPT分区形式”解决方法
windows·gpt
CoderIsArt1 天前
Windows图形开发库Kernel32,OpenGL32,Glu32,Gdi32与User32
windows
伪装成塔的小兵1 天前
Windows使用docker部署fastgpt出现的一些问题
windows·docker·容器·oneapi·fastgpt
开开心心就好1 天前
娱乐使用,可以生成转账、图片、聊天等对话内容
windows·python·智能手机·软件工程·娱乐·软件需求