How to prevent same process to be executed more than once at the same time?
Standard
Windows Forms applications can be launched multiple times and each instance
used completely independently from the others. However, sometimes it is required to restrict the user to run only a single instance of a program.
Process class
Process class contains a function that allows us to get the processes that
are currently executing in Windows. This class can be used to
find, is there any other instances of an application are running or not.
The following code is performing by checking the number
of matching processes and showing an error message if, another instance is already running. The method is then simply returned from to close the application. This
has to be done before the main form of the application is loaded.
static
void
Main()
{
// finding existing instances
string
processName = Process.GetCurrentProcess().ProcessName;
Process[]
instances = Process.GetProcessesByName(processName);
if
(instances.Length > 1)
{
MessageBox.Show("This application is already running!");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new
Form1());
}
|
The above code does work perfectly till we have not renamed application. But it does not work, if we renamed application.
For Example,
1.
Open application, lets assume named as “TestApp.exe”. So
now one instance of application started
2.
Rename “TestApp.exe” to “TestApp2.exe” and start
application. Now second instance also started. But this is not expected.
Let’s see how we can solve this problem also. We can
achieve this using Mutex as shown below,
using
System.Diagnostics;
using
System.Threading
[STAThread]
static void Main()
{
bool
createdNew;
Mutex
testMutex = new Mutex(true, "singleInstance",
out createdNew);
if
(createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
testMutex.ReleaseMutex();
}
else
{
MessageBox.Show("This application is already running.");
return;
}
}
Here, "createdNew" variable will be assigned to false if the mutex object is already created. So, even though we renamed application and start again this will restrict from opening.
That's it, we are done now.
Comments
Post a Comment