只允许程序单实例运行

有时候,我们只能允许程序单实例运行,以免程序运行出错。可以通过使用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
相关推荐
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
研华嵌入式2 天前
如何在高通跃龙QCS6490 Arm架构上使用Windows 11 IoT企业版?
arm开发·windows·嵌入式硬件
带娃的IT创业者2 天前
Windows 平台上基于 MCP 构建“文心一言+彩云天气”服务实战
人工智能·windows·文心一言·mcp
csdn_aspnet2 天前
Windows Node.js 安装及环境配置详细教程
windows·node.js
摇滚侠2 天前
java语言中,list<String>转成字符串,逗号分割;List<Integer>转字符串,逗号分割
java·windows·list
Source.Liu2 天前
【Pywinauto库】12.2 pywinauto.element_info 后端内部实施模块
windows·python·自动化
Source.Liu2 天前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化
私人珍藏库2 天前
[Windows] FileOptimizer v17.1.0_一款文件批量压缩工具
windows·批量压缩
掘根2 天前
【CMake】List
windows·microsoft·list
TToolss2 天前
删除文件夹里的网盘图标
windows