WinBatch® Technical Support Forum

All Things WinBatch => WinBatch => Topic started by: pguild on April 24, 2023, 02:28:44 PM

Title: How stop application from running twice
Post by: pguild on April 24, 2023, 02:28:44 PM
Somehow my application seems to be opening twice. That happens when the user double-clicks its icon on the taskbar. What is the best and easiest way of stopping a program from starting twice?
Title: Re: How stop application from running twice
Post by: bottomleypotts on April 24, 2023, 10:12:51 PM
I open a file for write access. If I cannot successfully open the file the app is running elsewhere and I gracefully exit. This is helpful in network situations where only one copy of the app can run on the network.
Title: Re: How stop application from running twice
Post by: cssyphus on April 25, 2023, 07:04:10 AM
When the app starts, it has a particular window title: "WBT - My Own Application"

I immediately rename the window title to something unique to my app: "MyOwnApp"

Before I do that, however, I check to see if that window already winExist()s - if so, the app is already running and I quietly terminate (EXIT) the current instance.

To solve the problem of two copies being started almost instantaneously, I do the following:

1. N = random number from 1 to 9
2. timeDelay(0.N) - timeDelay for a random amount of time, in tenths-of-a-second
3. Test as above
4. Repeat steps 1-to-3
5. Continue with app

One of the copies should terminate if two were opened simultaneously.  It introduces a very slight delay to starting up the app, but it solves the duplicate-copies problem - and it really isn't very much time.

Title: Re: How stop application from running twice
Post by: JTaylor on April 25, 2023, 07:22:55 AM
I do a similar thing to cssyphus.

Jim
Title: Re: How stop application from running twice
Post by: jmburton2001 on April 25, 2023, 10:31:02 AM
I use this in my scripts and compiled executables and it works about 99.9% of the time.

Code (winbatch) Select
DirPath = DirScript ()
INIFile = "%DirPath%Control.ini"
Running = IniReadPvt ("General", "Running"," ", INIFile) ; Running 0 = NOT Running  1 = Running
If Running == "1" then RunState = "RUNNING"
If Running != "1" then RunState = "NOT RUNNING"

If Running == "1" then Message ("ERROR!", "Program already running...")
If Running == "1" then Exit
Running = IniWritePvt ("General", "Running","1", INIFile)


When (IF) it fails the quick fix is to delete the "Control.ini" file in the program/script directory.

EDIT -> At the end of the script/program in the "Exit" section I place this line:

Code (winbatch) Select
Running = IniWritePvt ("General", "Running","0", INIFile)
Title: Re: How stop application from running twice
Post by: kdmoyers on April 26, 2023, 12:48:29 PM
I do as cssyphus showed, though perhaps not as well.