Click here to Skip to main content
Click here to Skip to main content

Easily Create A Single Instance Application

, 11 Sep 2003
Rate this:
Please Sign up or sign in to vote.
Simply add this module to your VB.NET app, change the project start-up object to Main() and you have a single instance application.

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:

 
<PRE lang=vb.net>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
Web Developer
United States United States
Senior Software Engineer and Architect at Fractured Thinking. Fractured Thinking markets PostScript tools and components for the .NET developer.

Comments and Discussions

 
GeneralMy vote of 1 PinmemberMember 103420904-May-14 2:29 
GeneralMy vote of 1 Pinmembermsamy.earth5-Dec-13 7:31 
QuestionUse a mutex PinmemberPuddin Tame6-Oct-13 5:41 
GeneralMy vote of 1 PinmemberCoolVini16-Mar-13 23:40 
GeneralMy vote of 1 PinmemberLimitedAtonement11-Oct-11 4:45 
GeneralThe correct way to do this PinmemberMach0052-Apr-04 1:15 
GeneralRe: The correct way to do this Pinmemberdadda_mac2-Aug-05 11:25 
GeneralRe: The correct way to do this Pinmembercterrinw6-Sep-06 20:38 
GeneralThanks for the tip! PinsussAnonymous10-Nov-03 5:17 
GeneralRe: Thanks for the tip! PinmemberLimitedAtonement11-Oct-11 4:43 
QuestionWhat about Terminal server? Pinmembertosch17-Sep-03 2:39 
AnswerRe: What about Terminal server? PinmemberSteven Killick10-Nov-03 7:10 
GeneralRe: What about Terminal server? PinsussTim Eichman14-Jun-04 8:56 
GeneralNot Multi-User friendly PinsussAnonymous15-Sep-03 17:00 
GeneralCode Works As Expected PinmemberSteven Killick15-Sep-03 5:00 
GeneralNot really (Re: Code Works As Expected) PinsussA Helper18-Sep-03 4:24 
GeneralRe: Not really (Re: Code Works As Expected) PinsussAnother Helper18-Sep-03 4:39 
GeneralProcess Name is turncated PinsussAnonymous12-Sep-03 11:44 
GeneralSorry, it may not work the way you expected PinmemberXiangyang Liu12-Sep-03 11:40 
Generalsigh Pinmemberdog_spawn12-Sep-03 13:09 
GeneralYou could also try this Pinmemberppyrstr12-Sep-03 10:50 
GeneralRe: You could also try this Pinmemberandye5449415-Sep-03 17:09 
GeneralRe: You could also try this PinmemberMach0052-Apr-04 1:22 
GeneralRe: You could also try this Pinmembermjwills7-May-06 19:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 12 Sep 2003
Article Copyright 2003 by Steven Killick
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid