Link to home
Start Free TrialLog in
Avatar of hbh
hbh

asked on

How to keep only one program running

How can I keep only one windows program running in memory?
What should I check when this program starts running?
Avatar of Tommy Hui
Tommy Hui

Do you want only one Windows program running? Regardless of what that program is?

Which version of Windows are you referring to? 16-bit or 32-bits?
ASKER CERTIFIED SOLUTION
Avatar of alexo
alexo
Flag of Antarctica image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hbh

ASKER

Yes, I just want one window program running under windows 95,
a 32bit platform. An example called Spy++ in MSVisual C++ is
such as this kind of program, which has only one copy when it
is running.

Here's how I'd do it for Win32:

#pragma data_seg("myapplication")
BOOL g_bHasStarted;
#pragma

Then, in the initialization somewhere:

if(g_bHasStarted == 0) {
   g_bHasStarted = 1;
} else {
   Exit();   /* or your cleanup routine. */
}


that works too but only if you instruct the linker to make the "myapplication" segment shared, *and* initialize the global variable.

Something like:

#pragma comment(linker, "/section:myapplication,rws")
#pragma data_seg("myapplication")
BOOL g_bHasStarted = 0;
#pragma data_seg()

However, it relies on #pragmas specific to the MSVC compiler and thus is less portable.

I'd suggest relying on a named object or a global atom.

Something like:

    hMutex = CreateMutex (NULL, FALSE, "Some unique name");
    if ((hMutex != NULL) && (GetLastError () == ERROR_ALREADY_EXISTS)) {
        MessageBox (NULL, "Another instance of this application is running",
            "Error", MB_OK | MB_ICONSTOP);
        CloseHandle (hMutex);
        return -1;
    }

In the beginning of your program, and:

    CloseHandle (hMutex);

At the end.

Avatar of hbh

ASKER

I have adopted alexo's method. It is simple and effictive.
Thanks.