How-to prevent an Application from running more than once.
How-to prevent an Application from running more than once.
In VS.NET 2003 I often need an application to run as Singleton, meaning - run only once. This is a typical behavior of servers. Unfortunately, there is no support for this in Framework 1.1 .
So here is an elegant solution. The code is in C#, but may be applied to VB.NET as well.
The Code - Option 1
This will prevent an application from running more than once:
--------------------------------------------
using System.Threading;
using System.Runtime.InteropServices;
public class Form1 : Form
{
(...)
[STAThread]
static void Main()
{
bool createdNew;
Mutex m = new Mutex(true, "YourAppName", out createdNew);
if (! createdNew)
{
// app is already running...
MessageBox.Show("Only one instance of this application is allowed at a time.");
return;
}
Application.Run(new Form1());
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}
}
------------------------------------------
This code is added to the Main method (In VB.NET you will need to create one, click here to see how).
Notice: Make sure that you set a unique name for the application instead of YourAppName in the mutex decleration in my code (or you will prevent other applications from running).
The Code - Option 2
The next section will close the PREVIOUS instance of the application:-------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
(...)
static void Main()
{
// get the name of the current process
Process currentProcess = Process.GetCurrentProcess();
string currProcessName = currentProcess.ProcessName;
// get all instances of the this application
Process[] prevAppInstance = Process.GetProcessesByName(currProcessName);
// kill all other instances of this application
for(int i = 0 ; i {
if(prevAppInstance[i].Id != currentProcess.Id)
{
prevAppInstance[i].Kill();
}
}
// run the aplication
Application.Run(new Form1());
}
-------------------------
In this case you will close the instance that is running and keep the new one running (sometimes this bevior is more appropriate).
For more discussion, click here
2 Comments:
You can do it also in this way:
using System.Collection.Generic;
using System.Windows.Forms;
using System.Diagnostic.*;
public class Program
{
public static void main(String[] args)
{
String name = Process.GetCurrentProcess().ProcessName;
Process[] procs = GetProcessesByName(name);
if(procs.length > 1)
return;
Application.Run(new Form1());
}
}
It works very well.
The third solution seems like a race condition to me. The result may be situations where no application will run at all.
Post a Comment
<< Home