Click here to Skip to main content
6,292,811 members and growing! (10,523 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate

Easily Create A Single Instance Application

By Steven Killick

Simply add this module to your VB.NET app, change the project start-up object to Main() and you have a single instance application.
VB, Windows, .NET 1.1, Visual Studio, Dev
Posted:11 Sep 2003
Views:68,559
Bookmarked:8 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
21 votes for this article.
Popularity: 1.96 Rating: 1.49 out of 5
15 votes, 71.4%
1

2
2 votes, 9.5%
3
3 votes, 14.3%
4
1 vote, 4.8%
5

Introduction

Sometimes you want your application to run single instance. For example, if you wrote a server application you probably only want a single instance to run at a time on the localhost.

This code was developed primarily for a server application running on a Win2KPro Multi-Processor server. It is intended to make absolutely certain that only one instance of the application runs at a time regardless of logged on users. The code detects all processes running in all desktops and all service executables as well and will not start another process if one is already running.

There is an easy way to start an application so that it first checks to see if another application (process) of the same name is already running.

Create a new module as below and:

1) Add the module to your WinForm application project
2) Change the 'MyAppName' occurences as appropriate
3) Change the name of the form to start the application with [Application.Run(New MainForm)]
4) Change the StartupObject in the project properties to Main()


That's all it takes. Have fun.

Take a look at the code:

 
Imports System.Diagnostics 
Module SingleInstance

   'Entry point for the application. Main checks for a prior instance and closes

   'this one if it finds a prior one running.

   Public Sub Main() 

        If CheckForDuplicateProcess("MyAppName") Then
            Dim dupProcess As String
            dupProcess = "There is another instance of MyAppName" & _
        " running on this machine." & vbCrLf & _
        "This new instance must close." & vbCrLf & vbCrLf & _
        "Only 1 instance of MyAppName can exist" & _
        " on a machine." & vbCrLf & vbCrLf
            
        MsgBox(dupProcess, MsgBoxStyle.Critical, "Duplicate Process Detected") 

            Application.Exit() 

        Else 
                 '****** Change The FormName Below *****

                 'Change the name of the form to load, to the one 

                 'applicable for your application

            Application.Run(New MainForm)
    End If 
   End Sub
   'Determines if there already is a 'processName' running in the local host.

   'Returns true if it finds more than 'one processName' running

   Private Function CheckForDuplicateProcess(ByVal processName As String) As Boolean
        'function returns true if it finds more than one 'processName' running

        Dim Procs() As Process
        Dim proc As Process
    'get ALL processes running on this machine in all desktops

    'this also finds all services running as well.
         Procs = Process.GetProcesses()
         Dim count As Integer = 0
         For Each proc In Procs
             If proc.ProcessName.ToString.Equals(processName) Then
                count += 1
             End If
         Next proc
        If count > 1 Then
             Return True
         Else
            Return False
         End If
     End Function
 End Module

The example code has been tested on Win2K Pro and WinXP Pro. In all cases
it works as expected. No failures of any kind thus far.

Some readers have had a few comments and I have tried to reply to them below.

ProcessName Truncation By OS


The Process.ProcessName that CheckForDuplicateProcess() uses to loop thru all running processes is the same as the process name used in Task Manager. So if you have an exe named me.exe, and if you start two instances of it, you'll see two processes called 'me' in the task manager. They are not truncated in the task manager so using ProcessName works as expected.

On Using A Mutex To Obtain A Lock


I did not use the Mutex method because it would not be reliable on a multi-processor machine. If the original process was running on processor 1 and a duplicate process was started and attached to processor 2 then both would get a successful lock and you would have two processes running when you only want 1. Looping thru all the running processes is the only reliable way to prevent duplicate processes from starting. The Mutex method has less typing but is not a good solution for this problem.

On The Question Of Two Instances Starting At The Same Moment


Two instances starting at exactly the same moment on a single processor machine is impossible. And very very unlikely on a multi-processor machine. So unlikely in fact that we need not even worry about it in this situation.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Steven Killick


Member
Senior Software Engineer and Architect at Fractured Thinking. Fractured Thinking markets PostScript tools and components for the .NET developer.
Occupation: Web Developer
Location: United States United States

Other popular .NET Framework articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 18 of 18 (Total in Forum: 18) (Refresh)FirstPrevNext
GeneralThe correct way to do this PinmemberMach0052:15 2 Apr '04  
GeneralRe: The correct way to do this Pinmemberdadda_mac12:25 2 Aug '05  
GeneralRe: The correct way to do this Pinmembercterrinw21:38 6 Sep '06  
GeneralThanks for the tip! PinsussAnonymous6:17 10 Nov '03  
GeneralWhat about Terminal server? Pinmembertosch3:39 17 Sep '03  
GeneralRe: What about Terminal server? PinmemberSteven Killick8:10 10 Nov '03  
GeneralRe: What about Terminal server? PinsussTim Eichman9:56 14 Jun '04  
GeneralNot Multi-User friendly PinsussAnonymous18:00 15 Sep '03  
GeneralCode Works As Expected PinmemberSteven Killick6:00 15 Sep '03  
GeneralNot really (Re: Code Works As Expected) PinsussA Helper5:24 18 Sep '03  
GeneralRe: Not really (Re: Code Works As Expected) PinsussAnother Helper5:39 18 Sep '03  
GeneralProcess Name is turncated PinsussAnonymous12:44 12 Sep '03  
GeneralSorry, it may not work the way you expected PinmemberXiangyang Liu12:40 12 Sep '03  
Generalsigh Pinmemberdog_spawn14:09 12 Sep '03  
GeneralYou could also try this Pinmemberppyrstr11:50 12 Sep '03  
GeneralRe: You could also try this Pinmemberandye5449418:09 15 Sep '03  
GeneralRe: You could also try this PinmemberMach0052:22 2 Apr '04  
GeneralRe: You could also try this Pinmembermjwills20:12 7 May '06  

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

PermaLink | Privacy | Terms of Use
Last Updated: 11 Sep 2003
Editor:
Copyright 2003 by Steven Killick
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project