Make sure your application is single-instance (Windows).

Share your advanced PureBasic knowledge/code with the community.
Quin
Addict
Addict
Posts: 1126
Joined: Thu Mar 31, 2022 7:03 pm
Location: Colorado, United States
Contact:

Make sure your application is single-instance (Windows).

Post by Quin »

I saw someone asking how to make a single-instance Windows application, so threw together a super tiny module to do it. Usage is pretty self-explanatory, just call InitSingleInstance() in your initialization and FreeSingleInstance() in your shutdown logic.

Code: Select all

; Prevent multiple instances of your application from running at any given time (Windows only).
; Written by Quin, Thursday, March 28, 2024.

CompilerIf #PB_Compiler_IsMainFile
	EnableExplicit
CompilerEndIf

;{ Internal globals
Global SingleInstance_Mutex
;} End globals

;{ Declares
Declare InitSingleInstance(Slug$ = "")
Declare FreeSingleInstance()
;} End declares

;{ Procedures
Procedure InitSingleInstance(Slug$ = "")
	If Slug$ = ""
		Slug$ = GetFilePart(ProgramFilename(), #PB_FileSystem_NoExtension) + "_Running"
	EndIf
	SingleInstance_Mutex = CreateMutex_(0, 1, Slug$)
	If GetLastError_() = #ERROR_ALREADY_EXISTS
		MessageRequester("Error", "Another instance is already running.", #PB_MessageRequester_Error)
		End 1
	EndIf
EndProcedure

Procedure FreeSingleInstance()
	ReleaseMutex_(SingleInstance_Mutex)
EndProcedure
;} End procedures

;{ Test
CompilerIf #PB_Compiler_IsMainFile
	InitSingleInstance()
	MessageRequester("", "Now running.")
	FreeSingleInstance()
CompilerEndIf
;} End test
Hopefully it helps someone! :)