0

Could someone show how it is possible to check whether another instance of the program (e.g. my_prog_1.exe) is running and if so stop the application from loading if there is an existing instance of it With Different File Name (e.g. my_prog_2.exe).
both assemblies are the same, but their file name is different.

please see this thread :
c-sharp-how-to-check-if-another-instance-of-the-application-is-running
in this thread the answer checks the file names, but i need another parameter other than file names...

Community
  • 1
  • 1
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 3
    Use `mutex` like described [here](http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application) and [here](http://sanity-free.org/143/csharp_dotnet_single_instance_application.html). – Rohit Vats Jan 01 '14 at 18:45
  • A word of caution regarding the second link posted by @Rohit: Do **not** copy the GUID (`{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}`) as is, but rather create a new one (VS: Tools -> Create GUID). [GUID](http://en.wikipedia.org/wiki/Globally_unique_identifier)s - as the name implies - are unique. – IInspectable Jan 01 '14 at 18:57
  • True also you can append your company URL to it. – Rohit Vats Jan 01 '14 at 19:00
  • 1
    thank you guys! interesting! works like a charm:) please put your comment as answer @Rohit Vats – SilverLight Jan 01 '14 at 19:07
  • Sure, i have put the comment as an answer.. :) – Rohit Vats Jan 02 '14 at 06:47

1 Answers1

2

You can use Mutex like described here to achieve single instance of an application. For the sake of completeness, i am posting the code here in case link gets stale.

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    static void Main() {
        if(mutex.WaitOne(TimeSpan.Zero, true)) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            mutex.ReleaseMutex();
        } else {
            MessageBox.Show("only one instance at a time");
        }
    }
}

Also make sure like i mentioned in comment generate new GUID and can append company URL so that you always lock on unique object for your application.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185