Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 25,705 times

Related Categories

Prevent Multiple Instances

TerryRogers

This code shows how to avoid loading a second instance of an application when the user already has one instance running. It also sets the focus to the first instance of the Visual Basic application when you attempt to start a second instance of the same application.

Option Explicit

     Public Const GW_HWNDPREV = 3

     Declare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As Long
     Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
       (ByVal lpClassName As String, ByVal lpWindowName As String) _
        As Long
     Declare Function GetWindow Lib "user32" _
       (ByVal hwnd As Long, ByVal wCmd As Long) As Long
     Declare Function SetForegroundWindow Lib "user32" _
       (ByVal hwnd As Long) As Long

     Private Sub Form_Load()
           If App.PrevInstance Then
              ActivatePrevInstance
           End If
        End Sub

     Sub ActivatePrevInstance()
        Dim OldTitle As String
        Dim PrevHndl As Long
        Dim result As Long

        'Save the title of the application.
        OldTitle = App.Title

        'Rename the title of this application so FindWindow
        'will not find this application instance.
        App.Title = "unwanted instance"

        'Attempt to get window handle using VB4 class name.
        PrevHndl = FindWindow("ThunderRTMain", OldTitle)

        'Check for no success.
        If PrevHndl = 0 Then
           'Attempt to get window handle using VB5 class name.
           PrevHndl = FindWindow("ThunderRT5Main", OldTitle)
        End If

        'Check if found
        If PrevHndl = 0 Then
        'Attempt to get window handle using VB6 class name
        PrevHndl = FindWindow("ThunderRT6Main", OldTitle)
        End If

        'Check if found
        If PrevHndl = 0 Then
           'No previous instance found.
           Exit Sub
        End If

        'Get handle to previous window.
        PrevHndl = GetWindow(PrevHndl, GW_HWNDPREV)

        'Restore the program.
        result = OpenIcon(PrevHndl)

        'Activate the application.
        result = SetForegroundWindow(PrevHndl)

        'End the application.
        End
     End Sub

Comments

  • Re: How to -- in C#?

    Posted by e.kmanohar on 08 Jul 2006

    In Asp.Net How Can Prevent To User Can't Open more than one window of same site on same machin.plz give me right solution and code in c# ASAP.


    Thanks & Regards


     Kunal Manoh...

  • How to -- in C#?

    Posted by inferano on 07 Feb 2006

    Can I get to know, how this can be done in C# for a Windows Application as an Example?

  • Can't you just...

    Posted by mrjdesign on 19 Jun 2004

    Private Sub Main()
    If App.PrevInstance Then End
    'won't get here if Ended
    Call MainFormLoad ' whatever you name it to initialize your app
    End Sub