|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionMany times in developing Windows Forms and Web applications, we would wish that user need not open multiple instances of the applications and restrict to a single instance alone. Perhaps we end solving this problem by locking redundant code in each of the applications, we develop, which are designed at that time, exclusively for that purpose. In this article, we would see how we can make an elegant use of Now, we shall see how to solve this problem for a Windows Form and ASP.NET web application. Solving for Windows Forms applicationFor a Windows Form application, we need to just add a simple public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
At the start of the application, since this is a static method, you can use a simple if condition if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
Alternate solution for Windows Forms using System.Threading conceptsThere is also one more cute solution, as one mav.northwind suggested in the forums. I just tested it with my demo and test application and it works fine. Perhaps, for the benefit of the reader, I am just trying to reproduce the code snippet of mav.northwind over here. Thank you mav.northwind!!! using System.Threading;
//[...]
private static Mutex s_Mutex;
and then use this in your Main() method:
s_Mutex = new Mutex(true, "YourMutexNameGoesHere");
if (s_Mutex.WaitOne(0,false))
Application.Run(new Form1());
else
MessageBox.Show("Another instance running");
Solving for web applicationsFor web applications, the approach we need to take would be a bit different. When the application starts and perhaps normally in the login page, you can set a cookie via JavaScript. Perhaps in some common application framework file like Header, Footer etc, you can check this cookie via JavaScript or server. If the cookie does match the criteria for the session, then you may optionally close the window after informing the user suitably. Conclusion:I hope the above would really help .net Windows programmers and web application developers fraternity worldwide in resolving quite a common issue of detecting duplicate instances of the applications and handling them with ease.
|
||||||||||||||||||||||