5,317,598 members and growing! (25,315 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate License: The Code Project Open License (CPOL)

Restricting Application to a Single Instance

By Vasudevan Deepak Kumar

In this article, we would discuss very breifly on how to restrict an application to a single instance, be it a Windows Forms or Web application.
C#, VB, Windows, .NET 1.0, .NET, Visual Studio, ASP, ASP.NET, Dev

Posted: 20 Mar 2003
Updated: 20 Mar 2003
Views: 70,055
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
18 votes for this Article.
Popularity: 3.26 Rating: 2.60 out of 5
7 votes, 38.9%
1
0 votes, 0.0%
2
3 votes, 16.7%
3
2 votes, 11.1%
4
6 votes, 33.3%
5

Introduction

Many 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 System.Reflection namespace to detect whether an instance of an application is already running. Actually, I was in need of a similar situation for my web application and hence I was searching through various forums. I encountered this System.Reflection strategy in one of the premiere .NET forums, following which, I designed by cookie-centric strategy for Web Application.

Now, we shall see how to solve this problem for a Windows Form and ASP.NET web application.

Solving for Windows Forms application

For a Windows Form application, we need to just add a simple static method in our application, which can examine all the processes running over the system and if the concerned application image name is found, it will inform the user and take an appropriate route, meaning, it would either warn the user of duplicate invocation of the program and proceed according to user intervention like WinZip or reuse existing instance like HTMLKit IDE. Perhaps you may use the following code snippet in your application.

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 concepts

There 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 applications

For 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vasudevan Deepak Kumar


Vasudevan Deepak Kumar is from Chennai, India who has been in the programming career since 1994, when he was 15 years old. He has his Bachelors of Engineering (in Computer Science and Engineering) from Vellore Engineering College (now VIT University). He also has a MBA in Systems from Alagappa University, Karaikudi, India.


He started his programming career with GWBasic and then in his college was involved in developing programs in Fortran, Cobol, C++. He has been developing in Microsoft technologies like ASP, SQLServer 2000. For sometime, he has also been with PHP and MySQL based development in one of his previous organizations. Now currently his focus is on Microsoft .NET World (ASP.NET, C# and Whidbey)


In his past-time, he listens to polite Carnatic Music.

Web Presence



Homepage

http://www.lavanyadeepak.tk/

Blogs



Technical




Gossips




Spiritual







Occupation: Web Developer
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionNeed Helpmembersuryahg21:01 2 Jul '08  
GeneralUsing the form from second instancememberMorar Sebastian3:50 20 Sep '06  
GeneralPlagiarism?memberNetworkArchitek12:18 1 Feb '06  
GeneralRe: Plagiarism?memberVasudevan Deepak Kumar22:55 1 Feb '06  
GeneralAlternatives for .NET CF?memberandroboy0:25 9 Sep '03  
GeneralRe: Alternatives for .NET CF?sussJoel Aemmer11:50 17 Aug '04  
GeneralTaking it furthersussAnonymous0:54 18 Apr '03  
GeneralRe: Taking it furthermemberDeepak Kumar Vasudevan1:08 18 Apr '03  
GeneralRe: Taking it furthermembermarkpirvine1:20 18 Apr '03  
GeneralRe: Taking it furthersussAnonymous6:59 2 Mar '05  
GeneralMuch easier and more consistent waymembermav.northwind21:19 20 Mar '03  
GeneralRe: Much easier and more consistent waymemberDeepak Kumar Vasudevan21:37 20 Mar '03  
GeneralRe: Much easier and more consistent waysussAnonymous10:06 21 Mar '03  
GeneralRe: Much easier and more consistent waymemberdog_spawn18:06 21 Mar '03  
GeneralRe: Much easier and more consistent waymemberBrett Robichaud7:48 24 Mar '03  
GeneralRe: Much easier and more consistent waymemberjamshidmf4:23 29 Apr '03  
GeneralRe: Much easier and more consistent waymemberCoder-9:05 29 Jul '03  
GeneralRe: Much easier and more consistent waysussAnonymous7:00 15 Oct '03  
GeneralRe: Much easier and more consistent waysussAlireza Haghshenass7:01 15 Oct '03  
GeneralRe: Much easier and more consistent waymemberJunky6911:13 17 Mar '08  
GeneralRe: Much easier and more consistent waymemberwhosit12:32 31 Mar '03  
GeneralRe: Much easier and more consistent waymemberjosh_heller6:58 3 Jun '03  
GeneralRe: Much easier and more consistent waymemberStXh18:15 6 Aug '03  
GeneralRe: Much easier and more consistent waymemberMach0057:34 2 Apr '04  
GeneralRe: Much easier and more consistent waymembersnorkie12:05 23 Jan '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Mar 2003
Editor: Smitha Vijayan
Copyright 2003 by Vasudevan Deepak Kumar
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project