Click here to Skip to main content
15,885,038 members
Articles / Programming Languages / Visual Basic
Article

Easily Create A Single Instance Application

Rate me:
Please Sign up or sign in to vote.
1.17/5 (26 votes)
11 Sep 20032 min read 116.1K   398   11   24
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:

VB.NET
<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 
VB.NET
End Sub
VB.NET

VB.NET

VB.NET
'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
VB.NET
'get ALL processes running on this machine in all desktops
'this also finds all services running as well.
VB.NET
        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


Written By
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 Pin
Member 103420904-May-14 2:29
Member 103420904-May-14 2:29 
GeneralMy vote of 1 Pin
msamy.earth5-Dec-13 7:31
msamy.earth5-Dec-13 7:31 
QuestionUse a mutex Pin
Puddin Tame6-Oct-13 5:41
Puddin Tame6-Oct-13 5:41 
GeneralMy vote of 1 Pin
CoolVini16-Mar-13 23:40
CoolVini16-Mar-13 23:40 
GeneralMy vote of 1 Pin
LimitedAtonement11-Oct-11 4:45
LimitedAtonement11-Oct-11 4:45 
GeneralThe correct way to do this Pin
Mach0052-Apr-04 1:15
Mach0052-Apr-04 1:15 
GeneralRe: The correct way to do this Pin
dadda_mac2-Aug-05 11:25
dadda_mac2-Aug-05 11:25 
GeneralRe: The correct way to do this Pin
cterrinw6-Sep-06 20:38
cterrinw6-Sep-06 20:38 
GeneralThanks for the tip! Pin
Anonymous10-Nov-03 5:17
Anonymous10-Nov-03 5:17 
GeneralRe: Thanks for the tip! Pin
LimitedAtonement11-Oct-11 4:43
LimitedAtonement11-Oct-11 4:43 
This post is completely incorrect. Do not use this information for your program, find another source of information.
In Christ,
Aaron Laws

http://ProCure.com

QuestionWhat about Terminal server? Pin
tosch17-Sep-03 2:39
tosch17-Sep-03 2:39 
AnswerRe: What about Terminal server? Pin
Steven Killick10-Nov-03 7:10
Steven Killick10-Nov-03 7:10 
GeneralRe: What about Terminal server? Pin
Tim Eichman14-Jun-04 8:56
Tim Eichman14-Jun-04 8:56 
GeneralNot Multi-User friendly Pin
Anonymous15-Sep-03 17:00
Anonymous15-Sep-03 17:00 
GeneralCode Works As Expected Pin
Steven Killick15-Sep-03 5:00
Steven Killick15-Sep-03 5:00 
GeneralNot really (Re: Code Works As Expected) Pin
A Helper18-Sep-03 4:24
sussA Helper18-Sep-03 4:24 
GeneralRe: Not really (Re: Code Works As Expected) Pin
Another Helper18-Sep-03 4:39
sussAnother Helper18-Sep-03 4:39 
GeneralProcess Name is turncated Pin
Anonymous12-Sep-03 11:44
Anonymous12-Sep-03 11:44 
GeneralSorry, it may not work the way you expected Pin
Xiangyang Liu 刘向阳12-Sep-03 11:40
Xiangyang Liu 刘向阳12-Sep-03 11:40 
Generalsigh Pin
dog_spawn12-Sep-03 13:09
dog_spawn12-Sep-03 13:09 
GeneralYou could also try this Pin
ppyrstr12-Sep-03 10:50
ppyrstr12-Sep-03 10:50 
GeneralRe: You could also try this Pin
andye5449415-Sep-03 17:09
andye5449415-Sep-03 17:09 
GeneralRe: You could also try this Pin
Mach0052-Apr-04 1:22
Mach0052-Apr-04 1:22 
GeneralRe: You could also try this Pin
mjwills7-May-06 19:12
mjwills7-May-06 19:12 

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

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