Ensuring only one instance of your application runs at once

by Andrew Jackson 18. November 2005 17:06

In your main form put the following piece of code, replacing the YOURMAINFORM with the name of the form.

Shared Sub Main() ' check for previous instance If PrevInstance() Then MsgBox("Application is already running!", MsgBoxStyle.OKOnly Or MsgBoxStyle.Critical) Else ' Runs the application. Application.Run(New YOURMAINFORM) End If End Sub Private Shared Function PrevInstance() As Boolean ' array of running processes with this assembly name Dim p() As Process = Nothing Try ' put the processes into an array p = Diagnostics.Process.GetProcessesByName(System.Reflection.Assembly.GetExecutingAssembly.GetName.Name()) ' if there's more than one process with this name If p.Length > 1 Then ' program is running...return True PrevInstance = True Else PrevInstance = False End If Catch ex As System.Exception ' set return to False PrevInstance = False Finally ' clean up p = Nothing End Try End Function

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen