Prevent the second instance of application be excuted

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,

I have a winform application and I need to have only one instance of it all
times.
How can I determin if the application is being ran? So I can bring up the
previous instace?

Thanks,
Alam
 
Use a named mutex to restrict to one running instance:

[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(false, appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}

Application.Run(new Form1());
}
}

private static string appGuid = aUniqueId;

There are some other complications if you to prevent different
security contexts from running the same instance, or if you are in a
terminal services scenaio.

For bringing up the previous instance you'll have some more work to
do. I believe you'll have to PInvoke SetForegroundWindow, or
ShowWindow if the app is minimized.
 
Back
Top