Tuesday, 22 October 2013

Single Instance Application VB.NET

'How to check / Allow only one instance of Application is Running.

Imports System.Diagnostics
Module mdlMain

    Public Sub main()
        Application.EnableVisualStyles()
        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

    '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 Reflection.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


End Module