Prevent Openning the program twice

  • Thread starter Thread starter C# Learner
  • Start date Start date
I made a gui program with c# but i want even if people double click my
program more than once it would only open once
is something like that possible if it is how?
 
Process currentProcess = Process.GetCurrentProcess();
if(Process.GetProcessesByName(currentProcess.ProcessName,
currentProcess.MachineName).Length>1)
{
Console.Write("Already running");
Console.Read();
}

Gabriel Lozano-Morán
 
Tolga Tanriverdi said:
I made a gui program with c# but i want even if people double click my
program more than once it would only open once
is something like that possible if it is how?

Use a global mutex to identify your running instance.
This way you prevent running multiple instances machine wide.

bool freeToRun;
string safeName = "Global\\StringUniquelyIdentifyingThisApplication";
using(System.Threading.Mutex m = new System.Threading.Mutex(true, safeName
, out freeToRun))
{
if (freeToRun)
Application.Run (new MainForm());
MessageBox.Show("Already running...", safeName);
}

Willy.
 
25/04/2005 10.29.30
Process currentProcess = Process.GetCurrentProcess();
if(Process.GetProcessesByName(currentProcess.ProcessName,
currentProcess.MachineName).Length>1)
{
Console.Write("Already running");
Console.Read();
}

Gabriel Lozano-Morán

Gabriel, this is not a good way for several reasons (also MSDN
indicates this limits): it couldn't work due to limited user rights,
or if performance counters are disabled. The best solution is to use
mutex, as indicated by Willy...also in VB2005 implementation they use
mutex!
 
Aah so in the 2005 we can get Application Previous instance easier right?
 
Willy I think that what he is trying to say is that in VB6 we have
App.PrevInstance and it would be a nice addition to future versions of the
..NET base class library to have something similar.

Gabriel Lozano-Morán
 
LOZANO-MORÁN said:
Willy I think that what he is trying to say is that in VB6 we have
App.PrevInstance and it would be a nice addition to future versions of the
.NET base class library to have something similar.

Gabriel Lozano-Morán

The problem with App.PrevInstance is that it fails in a TS environment and
that it can't be used for non windows applications.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top