From a windows .net application is it possible to detect if the application is already running?
I am developing a windows .net program (in c#) and I was wondering if it is possible to detect on startup if the program is already running, so that the user is not allowed to run two instances of it at once?
How is that done?
Status:
Open Jul 03, 2007 - 10:06 AM
windows, .net, information technology, C#
3answers
Answers
Jul 03, 2007 - 12:25 PM
Yes, this is possible. You have to use System.Threading.Mutex. This is a system wide handle for an application. A mutex has a system wide mutex name i.e. "MYAPPLICATION". You can check for the mutex and if it exists, you know that your application is already running and you can react accordingly. Here is an example from a book:
using System.Threading;
class Program
{
static void Main(string[] args)
{
Mutex oneMutex = null;
const string MutexName = "RUNMEONLYONCE";
try // Try and open the Mutex
{
oneMutex = Mutex.OpenExisting(MutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
// Cannot open the mutex because it doesn't exist
}
// Create it if it doesn't exist
if (oneMutex == null)
{
oneMutex = new Mutex(true, MutexName);
}
else
{
// Close the mutex and exit the application
// because we can only have one instance
oneMutex.Close();
return;
}
Console.WriteLine("Our Application");
Console.Read();
}
}
Let me know if this helped you!
Cheers
Peter
Jul 05, 2007 - 12:01 AM
Thanks, Peter. this is perfect!
Jul 24, 2007 - 10:26 AM
For VB.NET take Project Properties --> Enable Application Framework --> Windows Application Framework Properties --> Check in Make Single Instance Application
Answer this question
Share Your Own Experience & Expertise
We look to ensure that every question is answered by the best people with relevant expertise and experience, the best answers include multiple perspectives. Do you have relevant expertise or experience to contribute your answer to any of these commonly asked questions?
Add New Comment