只允许程序单实例运行

有时候,我们只能允许程序单实例运行,以免程序运行出错。可以通过使用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
相关推荐
黄交大彭于晏43 分钟前
发送文件脚本源码版本
java·linux·windows
vfvfb11 小时前
bat批量去掉本文件夹中的文件扩展名
服务器·windows·批处理·删除扩展名·bat技巧
我命由我1234517 小时前
VSCode - VSCode 放大与缩小代码
前端·ide·windows·vscode·前端框架·编辑器·软件工具
PT_silver17 小时前
tryhackme——Abusing Windows Internals(进程注入)
windows·microsoft
爱炸薯条的小朋友18 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
Lw老王要学习19 小时前
VScode 使用 git 提交数据到指定库的完整指南
windows·git·vscode
CodeOfCC1 天前
c语言 封装跨平台线程头文件
linux·c语言·windows
momo卡1 天前
MinGW-w64的安装详细步骤(c_c++的编译器gcc、g++的windows版,win10、win11真实可用)
c语言·c++·windows
南林yan2 天前
DLL动态库实现文件遍历功能(Windows编程)
windows
Mike_6662 天前
win10安装WSL2、Ubuntu24.04
windows·ubuntu·wsl2