Number of instances of a program.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

What is the cleverest way of preventing the user of a program to start more
than instance of the program.

regards Jesper.
 
Hi Jesper,

include the following code in the static void Main(string[] args) routine:

// start application
try {

// get the mutex

MyMutex = new System.Threading.Mutex(true, "Test", out Ownership);

// check, if a single instance of the programm runs

if(Ownership) {

Application.Run(new MainForm());

}

else {

System.Environment.Exit(-1);

}

// clean up the mutex

if(MyMutex != null) MyMutex.Close();

}

catch (Exception except) {

// clean up the mutex

if(MyMutex != null) MyMutex.Close();

System.Environment.Exit(-1);

}



Bye



Frank
 
Frank said:
include the following code in the static void Main(string[] args) routine:

Or, rather more succinctly:

bool owner;
using (Mutex mutex = new System.Threading.Mutex(true, "Test", out
owner);
{
if (owner)
{
Application.Run(new MainForm())
}
else
{
System.Environment.Exit(-1);
}
}

The "using" statement takes care of disposing of the Mutex.

Jon
 
Hello Jon Skeet [C# MVP],

Yep, and @"Global\Test" if we wanna single instance across sessions. Because
for terminal sessions each client gets unique namespace, where our code works

J> Frank wrote:
J>
include the following code in the static void Main(string[] args)
routine:
J> Or, rather more succinctly:
J>
J> bool owner;
J> using (Mutex mutex = new System.Threading.Mutex(true, "Test", out
J> owner);
J> {
J> if (owner)
J> {
J> Application.Run(new MainForm())
J> }
J> else
J> {
J> System.Environment.Exit(-1);
J> }
J> }
J> The "using" statement takes care of disposing of the Mutex.
J>
J> Jon
J>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
Back
Top