Single instance of App...

  • Thread starter Thread starter Dilip Krishnan
  • Start date Start date
D

Dilip Krishnan

Hi,
I was wondering if there was a way to make sure only one instance
of an app is running in memory in C#. To explain my point...

Consider an application like Winword, it only runs once in memory and
every time one opens winword a new document is opened but the same
instance of Winword is servicing the new document.

Thanks
 
My Windows Forms tips and tricks page has an example of how to do this and
how to bring the current instance of the application to the foreground at
the same time.

http://www.bobpowell.net/tipstricks.htm

--
Bob Powell [MVP]
Visual C#, System.Drawing

All you ever wanted to know about ListView custom drawing is in Well Formed.
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

Read my Blog at http://bobpowelldotnet.blogspot.com
 
Here's how I've dealt with this issue. I created a private class called
InstanceChecker within my main form as such:

private class InstanceChecker
{
System.Threading.Mutex mtx = new System.Threading.Mutex( true,
"SomeStringThatIsUnique");

public bool isRunning
{
get
{
bool result = false;

if ( mtx != null )
result = mtx.WaitOne( 1000, false );

return !result;
}
}

public void ReleaseMutex()
{
mtx.ReleaseMutex();
}
}

then for the Main entry point I have:

static void Main()
{
InstanceChecker myInstance = new InstanceChecker();

if ( !myInstance.isRunning )
{
Application.Run( new MainForm() );
myInstance.ReleaseMutex();
}
}

So the first time the app is run a mutex is created for the lifetime of
the first instance of the app. Any subsequent instances will find that
the mutex already exists and simply quit.

Hope that helps.
 
Back
Top