Check for Single-Instance

vckicks 1 Tallied Votes 253 Views Share

A simple way to check if the current C# program is the only instance of itself running.

private bool IsSingleInstance()
{
     foreach (Process process in Process.GetProcesses())
     {
          if (process.MainWindowTitle == this.Text)
               return false;
     }
     return true;
}
ashishkumar008 2 Light Poster

this give error....
In foreach line (in process)
always mention namespace which is required and that place where code to be paste

gusano79 247 Posting Shark

Simple, yes... but not something I'd allow into production code. See these links for some discussion.

Here's an alternative... first, a method to try to create a mutex unique to the application:

private Mutex GetSingleInstanceMutex()
{
    bool createdNewMutex;

    Mutex mutex = new Mutex(false, @"Global\" + SomethingUnique, out createdNewMutex);

    if (!createdNewMutex)
    {
        mutex = null;
    }

    return mutex;
}

SomethingUnique should be something unique to the application, for example, the assembly GUID.

Here's how you'd use the method:

using (Mutex mutex = GetSingleInstanceMutex())
{
    if (mutex != null)
    {
        // This is the only running instance; go ahead and run the application.
    }
    else
    {
        // Another instance is running; notify user and quit.
    }
}
ddanbe commented: Very informative for a learner like me! +5
ashishkumar008 2 Light Poster

Request:-
i want to use flash file in webbrowser like other resources like picture
i do not want to use full path (c:\programfile\).
can u post full c# code
please

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.