/*

usage: SetInstance("Unique sMutex", "Error Message", "Caption of Error Message", "Caption of window to look for, can be partial title.  If found will activate it.")
 
example: SetInstance("SomethingUnique", "Program is already running", "My Program Name", "My Uni")
         If program is already running, it will display in a messagebox "Program is already running", with a title of "My Program Name".  It will then search for a caption in which the left 6
         chars are "My Uni" and if found will activate it.  If not found it won't do anything.

example: SetInstance("SomethingUnique","","","My Unique Program")
         If the program is already running, it will find it and activate it, if "My Unique Program" matches the left 17 characters of the title.  If it can't find it, it won't do anything.

example: SetInstance("SomethingUnique","Program is already running", "My Program Name")
         If program is already running, it will display in a messagebox "Program is already running", with a title of "My Program Name".  It will then search for a caption that the left 15
         chars are "My Program Name" and if found will activate it.  If not found it won't do anything.

*/

sub SetInstance(string sMutex, string errmessage, string caption, OPT string windowtitle="")
	int iSuccess
	string searchtitle
	
	iSuccess = SingleInstance(sMutex)

	If iSuccess	'another instance is running
		if errmessage <> ""
			messagebox 0, errmessage, caption
		endif
		
		if windowtitle = ""
			searchtitle = caption
		else
			searchtitle = windowtitle
		endif
		
		EnumWindows(&FindTitleProc, &searchtitle)
		end
	endif
endsub

Sub SingleInstance(sOccurName as STRING), INT
	UINT hMutexOneInstance
	INT LastErr, ret = 0

	hMutexOneInstance = CreateMutexA(NULL, FALSE, sOccurName)
	LastErr = GetLastError()
	If (LastErr = 183) Or (LastErr = 5) Then
		ret = 1
	EndIf
	
	return ret
EndSub

sub FindTitleProc(HWND hwnd, LPARAM lParam)
	static string title	
	
	IF GetWindowText(hwnd, title, 254) > 0
		if ucase$(*<STRING>lParam) = ucase$(left$(title,len(*<STRING>lParam)))
			'found one, show it			
			SetForegroundWindow(hwnd)
			_ShowWindow(hwnd,SW_RESTORE)
			return FALSE	'stop searching
		endif
	endif
	return TRUE	'iterate through windows
endsub

