Click here to Skip to main content
15,118,172 members
Articles / Programming Languages / Visual Basic
Article
Posted 12 Oct 2003

Stats

88.8K views
33 bookmarked

Single Instance of Application

Rate me:
Please Sign up or sign in to vote.
3.52/5 (18 votes)
12 Oct 2003
Shows a very generic way to find out if another instance of the application is already running and activate the running instance's main window by bringing it to the foreground.

Introduction

Brief preamble: Some time ago I was looking for a way to find out if another instance of the application is already running. A trivial task as you may say and I would agree with you instantly as long as you are familiar with Win32 API. I looked around on various sites including this one and found a few interesting articles, including an article talking at length how to set up a well-known object to pass command line parameters to an existing instance (a good DDE replacement), which is nice but not exactly what I was looking for. I needed something quick and dirty and so here it goes.

VB
Public NotInheritable Class Win32Helper 
<System.Runtime.InteropServices.DllImport("user32.dll", _ 
EntryPoint:="SetForegroundWindow", _
CallingConvention:= Runtime.InteropServices.CallingConvention.StdCall, _
CharSet:=Runtime.InteropServices.CharSet.Unicode, SetLastError:=True)> _
Public Shared Function _ 
     SetForegroundWindow(ByVal handle As IntPtr) As Boolean
' Leave function empty
End Function

<System.Runtime.InteropServices.DllImport("user32.dll", _ 
EntryPoint:="ShowWindow", _
CallingConvention:=Runtime.InteropServices.CallingConvention.StdCall, _
CharSet:=Runtime.InteropServices.CharSet.Unicode, SetLastError:=True)> _
Public Shared Function ShowWindow(ByVal handle As IntPtr, _ 
                             ByVal nCmd As Int32) As Boolean
' Leave function empty 
End Function

End Class ' End Win32Helper 

Public Shared Function GetRunningInstance(ByVal _ 
                   processName As String) As Process
    Dim proclist() As Process = _ 
       Process.GetProcessesByName(processName)
    For Each p As Process In proclist
        If p.Id <> Process.GetCurrentProcess().Id Then
            Return p
        End If
    Next
    Return Nothing
End Function

'The main entry point for the application
Public Shared Sub Main()
    Dim pInstance As Process = _ 
      Win32Helper.GetRunningInstance(Process.GetCurrentProcess().ProcessName)
    If Not pInstance Is Nothing Then
        Dim handle As IntPtr = pInstance.MainWindowHandle
        If Not IntPtr.Zero.Equals(handle) Then
            Win32Helper.ShowWindow(handle, 1)
            Win32Helper.SetForegroundWindow(handle)
        End If
        Application.ExitThread()
    Else
        Dim context As ApplicationContext = _ 
           New ApplicationContext(New MainFrame) 
        Application.Run(context)
    End If
End Sub

Few last comments: I had to resort to a no-so-graceful approach (as compared to using remoting) as needed to activate a main window of the running instance if one was found. Mutexes wouldn't help either.

For those on a look out for any trace plagiarism I should perhaps add, this is my adaptation of already well known methods. This is just my humble contribution for others who may find this all somewhat useful.

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

Share

About the Author

petervn
United States United States
No Biography provided

Comments and Discussions

 
GeneralMain() function Pin
Anubhava Dimri12-Nov-08 0:18
MemberAnubhava Dimri12-Nov-08 0:18 
General4+ years later, exactly what I needed. Thx! (n/t) Pin
MacSpudster10-Dec-07 11:50
professionalMacSpudster10-Dec-07 11:50 
GeneralDoes not activate main window Pin
Deepak Sakpal14-Feb-07 23:58
MemberDeepak Sakpal14-Feb-07 23:58 
GeneralRe: Does not activate main window Pin
petervn2-May-07 18:19
Memberpetervn2-May-07 18:19 
GeneralExcellent Code Pin
Kestrel25-Oct-06 10:29
MemberKestrel25-Oct-06 10:29 
GeneralThanks Pin
Mr. Beasimer20-Jul-06 13:10
MemberMr. Beasimer20-Jul-06 13:10 
GeneralRe: Thanks Pin
LBeasimer18-Sep-06 8:23
MemberLBeasimer18-Sep-06 8:23 
Generalrestore from minimized state Pin
theCodeWrangler12-Apr-06 12:09
MembertheCodeWrangler12-Apr-06 12:09 
GeneralVery good code! Pin
Giakkomino4-Mar-06 6:56
MemberGiakkomino4-Mar-06 6:56 
GeneralNeeds Process Performance Counter Pin
jtencate7-Feb-06 9:47
Memberjtencate7-Feb-06 9:47 
GeneralSingle Instance Code Pin
Fade (Amit BS)7-May-05 4:24
MemberFade (Amit BS)7-May-05 4:24 
Dude,

Thanx for contributing this code.
don't mind what everyone else says, i , like you knew of a few ways to make this thing happen but wanted a short "dirty" way to do it.
your code (specifically the 'SetForegroundWindow' declaration) gave me what i needed.

thanx again for sharing this information.
becuase of ppl like you all of us can rest assured that we'll find just the code we are looking fore in here.

so that's a 5.

Fade (Amit BS)
QuestionHow can Start .exe program depending the Principal Process Pin
Vitoto4-May-05 11:24
MemberVitoto4-May-05 11:24 
GeneralValue of article Pin
Rede14-Oct-03 2:46
MemberRede14-Oct-03 2:46 

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.