Re: 2-Instance prevention

new topic     » goto parent     » topic index » view thread      » older message » newer message
lpuster said...

I thought I would find something in the archives or Forum about this.

If a user opens a second instance of my application, I would like to give focus to the first instance and exit the second instance without even opening a window. If I can't do that, at least give a meaningful error message.

I would prefer to work off a list of Windows tasks or list of open windows rather than using a zero-byte file or registry item as a switch. The switches can get out of sync and it is not easy to recover automatically. Win32Lib provides lots of resources for looking at windows, but it appears to only know about the current application.

Here is some code that I use a lot to make sure only one instance of any program gets launched, using semaphores, a type of shared memory. If any 2 programs attempt to create the exact same named semaphore, then the function terminates the second instance. I use the application's main window title, which in most cases is the program title and version number, but you can use any unique value. It could be expanded to pass focus to the initial application, as you requested, but this should get you started. Look in the archives for Pat Rat’s windows finding functions. http://www.rapideuphoria.com/window.zip

Yours, OtterDad

include Win32Lib.ew 
without warning 
 
-------------------------------------------------------------------------------- 
--  Window Window1 
constant Window1 = createEx( Window, "Semaphore Test", 0, Default, Default, 400, 300, 0, 0 ) 
--------------------------------------------------------- 
-------------------------------------------------------------------------------- 
-- allow only one instance of this program 
-- 
-- check for multiple calls - will confuse you by shutting down early 
atom one_already one_already = False 
 
global procedure only_one(atom local_hwnd) 
	object jk atom zCreateSemaphore, zGetLastError, zERROR_ALREADY_EXISTS 
	if one_already then warnErr("calling only one multiple times") end if 
	one_already = True 
 
	zCreateSemaphore = registerw32Function(kernel32,"CreateSemaphoreA", 
    	{C_POINTER,C_INT,C_INT,C_POINTER},C_INT) 
	zGetLastError = registerw32Function(kernel32,"GetLastError",{},C_INT) 
	zERROR_ALREADY_EXISTS = 183 
 
	-- create a semaphore for this instance 
	jk = w32Func(zCreateSemaphore,{NULL, 0, 1, 
    	allocate_string(getText(local_hwnd))}) -- make this any unique string 
	jk = w32Func(zGetLastError,{}) 
	if jk = zERROR_ALREADY_EXISTS then 
    	abort(0) -- abort if we're already running ! 
	else 
    	--warnErr("good 2 go") 
	end if 
 
	return 
end procedure 
 
only_one(Window1) 
 
WinMain( Window1,Normal ) 
 
new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu