# VBForums CodeBank > CodeBank - Visual Basic .NET >  VB.NET: Single Instance Application

## Shuja Ali

In VB 6, we had a very friendly App object which would give us lot of information  regarding the current application. If one wanted to check if there is already an instance of this application running it was just two lines of code. In VB.NET 2002/2003 we do not have any such object so to check whether we already have an instance of the application running we need to do some extra work. 

Here is a function which checks if the instance of the application is already running. If returns a Process object which contains information about the currently running instance or a null value(if the application is not running).
VB Code:
'Function : checkInstance
    'Input Parameter : None
    'Return Value : Returns the Process if the exe 
    'is already running or else returns nothing
    Public Function checkInstance() As Process
        Dim cProcess As Process = process.GetCurrentProcess()
        Dim aProcesses() As Process = process.GetProcessesByName(cProcess.ProcessName)
        'loop through all the processes that are currently running on the 
        'system that have the same name
        For Each process As Process In aProcesses
            'Ignore the currently running process 
            If process.Id <> cProcess.Id Then
                'Check if the process is running using the same EXE as this one
                If [Assembly].GetExecutingAssembly().Location = cProcess.MainModule.FileName Then
                    'if so return to the calling function with the instance of the process
                    Return process
                End If
            End If
        Next
        'if nothing was found then this is the only instance, so return null
        Return Nothing
    End Function
 We just have to call this function at the entry point of our application. If the return value is Null then this is the first instance and if it returns a process then we already have an instance of the application running on the system. Ideally a project will be started from Sub Main, so I would put the code in the Sub Main procedure.
VB Code:
Public Sub main()
        Dim tempProcess As Process
        tempProcess = checkInstance()
        If tempProcess Is Nothing Then
            Application.Run(New Form1)
        Else
            MessageBox.Show("Application is already running")
        End If
    End Sub
In case you want to set focus to the currently running instance then you can get the MainWindowHandle of the already running instance like this 
VB Code:
tempProcess.MainWindowHandle
 And then use SetForeGroundWindow Api to activate the already running instance.

Don't forget to Import System.Diagnostics namespace.

----------


## Shuja Ali

Another way of doing the same would be to use Threading. Associate a static Mutex with the thread that starts the application and then check for the same. Here is a sample 
VB Code:
Imports System.Threading
 Module Module1
    Private siMutex As Mutex
    Public Sub main()
        siMutex = New Mutex(False, "aUniqueName")
        If (Not siMutex.WaitOne(0, False)) Then
            MessageBox.Show("Application is Running")
        Else
            MessageBox.Show("Application Not Running")
            siMutex.ReleaseMutex()
        End If
    End Sub
End Module

----------


## Hack

You mention 2002/2003.

Does the same code work for/in 2005?

----------


## Shuja Ali

In VB 2005 checking making your application single instance has been made as easy as clicking a checkbox. And it even allows you to set the Focus to the already running instance without writing a single line of code.

Open Project Properties, and Select Application. Under Windows Application Framework properties check the "Make Single Instance Application" check box. Now if you build the project, your application will automatically become a single instance application.

And if you want to bring the already running instance to Foreground thats also easy. Trap the My.Application.StartupNextInstance event and set e.BringToForeground to true. 
VB Code:
Namespace My
    Partial Friend Class MyApplication
        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, _
ByVal e As _
Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            e.BringToForeground = True
        End Sub
    End Class
End Namespace
Isn't it easy.  :Smilie: 

I have started loving VB 2005.

----------


## Hack

Fine job!   :Thumb:

----------


## dee-u

> In VB 2005 checking making your application single instance has been made as easy as clicking a checkbox. And it even allows you to set the Focus to the already running instance without writing a single line of code.
> 
> Open Project Properties, and Select Application. Under Windows Application Framework properties check the "Make Single Instance Application" check box. Now if you build the project, your application will automatically become a single instance application.
> 
> And if you want to bring the already running instance to Foreground thats also easy. Trap the My.Application.StartupNextInstance event and set e.BringToForeground to true. 
> VB Code:
> Namespace My
>     Partial Friend Class MyApplication
>         Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, _
> ...


Without using Microsoft.VisualBasic can it be done also in C# Express 2005?

----------


## Shuja Ali

> Without using Microsoft.VisualBasic can it be done also in C# Express 2005?


 As far as I know C# Express 2005 does not give you that option. You still have to write code to do that. The above methods can be used in C# Express 2005 too.

----------


## Kasracer

> Without using Microsoft.VisualBasic can it be done also in C# Express 2005?


No. See my codebank submission: http://vbforums.com/showthread.php?t=397006

----------


## richardalgor

Just oneline code only

Dim _process() As Process _process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)

and check the _process.Length 

thats all

if you need full source code

http://net-informations.com/vbprj/fr...e-instance.htm

algor.

----------


## kilkenny

I take it that Process.GetProcessByName retrieves ALL matching processes that are running on the computer - regardless of which user the process is running under. If we only wanted to test to see if the is process is already running for the Current User - then how might we modify this (ie. the app is single instance per user, but want to permit someone to Switch User & run a new instance under a different account).

I'm assuming that comparing that any of the found processes .SessionID = current process .SessionID would do the trick, and permit the program to continue to run if they're not equal.

----------

