Single Program instance

In .NET 2.0 is there an easy way of ensuring you only have one instance of a Windows Forms app running at any one time?

Thanks

Graham

[138 byte] By [Gravy] at [2008-2-18]
# 1
If you are using Visual Basic then you can easily do via the following:

1. Right-click on My Project and click Open
2. Ensure Enable Application Framework is checked
3. Check Make single instance application

If you are using C# use can reference Microsoft.VisualBasic and then derive from Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase and set WindowsFormsApplicationBase.IsSingleInstance to true.

However, if you feel a little wierd referencing a VB dll from C#, you can visit CodeProject.com and there is a number of Single Instance applications on there.

Following is a google search that only searches Code Project for articles with Single Instance:

http://www.google.com.au/search?hl=en&q=single+instance+site%3Acodeproject.com&meta=

DavidM.Kean at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 2

wrote in message news:96411b41-31f9-4b3c-9c2f-2719bc0d368e@discussions.microsoft.com...

In .NET 2.0 is there an easy way of ensuring you only have one instance of a Windows Forms app running at any one time?

Thanks

Graham

Wrap your Application.Run call in a using block that encapsulates a global or a local Mutex, like in [1].

A global Mutex prevents multiple instances accross TS sessions, a local Mutex prevents multiple instances per TS session or non TS session.

[1]

bool okToRun;

// prevent multiple instances accross TS sessions

string uniqueAppId = "Global\\UniqueString";

using(Mutex m = new Mutex(true, uniqueAppId , out ok))

{

if (okToRun)

Application.Run (new MainForm());

}

Willy

MVPUser at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 3
For this I just found a great peice of code on the Code project that makes this much easier...
http://www.codeproject.com/csharp/singleinstance.asp
adwins04 at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified