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).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:
'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 FunctionIn case you want to set focus to the currently running instance then you can get the MainWindowHandle of the already running instance like thisVB 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 SubAnd then use SetForeGroundWindow Api to activate the already running instance.VB Code:
tempProcess.MainWindowHandle
Don't forget to Import System.Diagnostics namespace.




Reply With Quote