Click here to Skip to main content
6,595,854 members and growing! (22,544 online)
Email Password   helpLost your password?
Languages » VB.NET » Samples     Intermediate

VB.NET Code Package: Program Already Running

By George B Gilbert

Test at startup whether another instance of an application is already running, with three options for handling the situation.
VB, Windows, .NET, Visual Studio, Dev
Posted:9 Jan 2006
Views:55,595
Bookmarked:35 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
10 votes for this article.
Popularity: 3.94 Rating: 3.94 out of 5
1 vote, 10.0%
1

2

3
5 votes, 50.0%
4
4 votes, 40.0%
5

Demo project.

Option that does not allow a second copy of the application to run.

Option that lets the user run multiple copies of the application.

Contents

Introduction

Add this code to a VB.NET project when you want to test if another instance of the application is already running. You can either end the program, give the user the option to run the extra copy of the application, or make the previous copy of the application the active window.

The code is available in a package file for Double Text users, as well as in a text file for non-Double Text users.

Background

I set up the Program Already Running library because I found that determining whether or not an instance of an application is already running is something that I want in just about every project. In addition, the nature of each application dictates whether or not it's OK to allow multiple copies of the application to be running at the same time. The PAR library is a perfect example of simple code that I use often, but, code I don't want to spend any significant time on to add to each new project. Hence, the source file is set up to give me the ability to generate in seconds, the code I need, that is tailored to each new project.

Double Text Users

Library Summary

The Program Already Running (PAR) library consists of one source file (.DbC) and an overview (.DbO). The code in the source file is a protected sub that overrides a form's OnHandleCreated sub. Placing the code in this event allows the decision about what to do (when another copy of the application is already running) to be made before the form is loaded.

The source text is set up with selectable blocks of code so that each new copy of the sub can be customized during duplication to function as needed for your current project. In addition to including or not including Region statements, you can configure each new copy of the code to either:

  • alert the user and then end the new copy of the program,
  • give the user the option to let the additional instance of the application run, or
  • make the previous copy of the application the active window.

I also embedded two required responses, for the name of the developer and the name of the application, to be displayed in the message box text. There are two other markers (filler and date) that do not trigger dialog boxes during duplication.

The PAR source file generates fully commented code that is ready to compile.

  • The code was written with Option Strict On.
  • All versions of the repeated code have been tested multiple times.
  • The code is fully commented.
  • Region statements can be included or not included, each time the code is repeated.

Unwrapping The Library

  1. Download and unzip the package file. The package file is named Program Already Running.DbP.
  2. Unwrap the package in Double Text (File | Library Exchange | Unwrap). Save the library in an empty folder.

The library is ready to go. Repeat the code per the following instructions whenever you need a ready to compile copy. (If you don't like the way I've set up the source file, change it in the edit window.)

Using The Library

Repeating The Sub

Each time you need a copy of the sub procedure, follow these steps in Double Text. (These steps apply as written only if you do not change how the source file is set up.)

  1. In the main window, press F12 and browse to the PAR library.

  2. Click on the "OnHandleCreated Sub" title.

  3. In the Region window, click the All button to select both items if you want the Region statements included in your code, and then click OK. To exclude the region statements, just click OK.

  4. In the Options window, check only one item (to either end the program, give the user the option to continue, or make the previous copy of the program the active window), and then click OK.

  5. For the "Name of developer" prompt, enter your name and click OK (or press Enter). You can also just press Enter to accept the default name (mine).

  6. For the "Name of application" prompt, enter the name of the program as it is to be displayed in the message box and click OK (or press Enter).

  7. In the reminder window, click OK.

The ready to compile sub procedure is now on the clipboard. If you would like to review the code, press F4.

Add The Sub To Your Project

  1. In Visual Studio, open the code view for the project startup form.
  2. Place the insertion cursor where you want to add the override OnHandleCreated sub.
  3. Press Ctrl^V.

Repeating The API Declares

If you configured the sub to make the previous copy of the application the active window, you must add the supporting API Declares to the form. Follow these steps in Double Text.

  1. In the main window, press F12 and browse to the PAR library.

  2. Click on the "API Declares" title.

  3. In the reminder window, click OK.

Adding The API Declares To Your Project

  1. In Visual Studio, open the code view for the project startup form.
  2. Place the insertion cursor in the form's declarations section.
  3. Press Ctrl^V.

All of the above instructions for using the library (less the images) are in the library overview. Click on the Float button in the Double Text main window whenever you need a refresher. (If you change the source file, don't forget to reflect those changes in the overview.)

Non-Double Text Users

Demo And Text Files Summary

Download and unzip the demo file. Open the solution in Visual Studio. The demo project is coded to make the copy of the application that is already running the active window.

Download and unzip the text file. I repeated the three possible versions of the OnHandleCreated sub so there are three copies of the sub in separate text files ... PAR End Program, PAR Option To Run, and PAR Make Active Window. When you need this code, use whichever tool you prefer to make a copy of the appropriate text file, and then make any needed modifications. You might want to find and change the following either before or after you paste the code into your project in the startup form.

  • If you don't want the Region statements, delete them.
  • Change the date the code is added to your project.
  • Change the name of the developer.
  • Change the name of the application in the message box text.
  • If you are using the Make Active Window version, move the API Declare statements to the form's declarations section.

PAR End Program Code

This version of the sub ends the program after alerting the user that there is a copy of the application already running.

#Region " ... OnHandleCreated "
    Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        '------------------------------------------------------------

        '     Date          Developer            Code Change

        '  ---------- -------------------- --------------------------

        '  12/10/2005       G Gilbert            Original code

        '------------------------------------------------------------


        '------------------------------------------------------------

        ' Get all of the active processes for the application

        '------------------------------------------------------------

        Dim CurrentProcesses() As Process
        CurrentProcesses = Process.GetProcessesByName _
                           (Process.GetCurrentProcess.ProcessName)

        '------------------------------------------------------------

        ' If there is no previous copy

        ' of the application running, bail

        '------------------------------------------------------------

        If CurrentProcesses.GetUpperBound(0) <= 0 Then
            Exit Sub
        End If

        '------------------------------------------------------------

        ' Alert the user that a copy of the application

        ' is already running and then end

        ' this new instance with no recourse

        '------------------------------------------------------------

        Dim XMsg As String = "A copy of Your Application Name" & _
                             ControlChars.CrLf & _
                             "is already running"
        MessageBox.Show(XMsg, _
                   "Copy Running", _
                   MessageBoxButtons.OK, _
                   MessageBoxIcon.Exclamation)
        End

    End Sub
#End Region

PAR Option To Run Code

This version of the sub alerts the user that there is a copy of the application already running and gives the user the option to also run the copy just starting.

#Region " ... OnHandleCreated "
    Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        '------------------------------------------------------------

        '     Date          Developer            Code Change

        '  ---------- -------------------- --------------------------

        '  12/10/2005       G Gilbert            Original code

        '------------------------------------------------------------


        '------------------------------------------------------------

        ' Get all of the active processes for the application

        '------------------------------------------------------------

        Dim CurrentProcesses() As Process
        CurrentProcesses = Process.GetProcessesByName _
                           (Process.GetCurrentProcess.ProcessName)

        '------------------------------------------------------------

        ' If there is no previous copy 

        ' of the application running, bail

        '------------------------------------------------------------

        If CurrentProcesses.GetUpperBound(0) <= 0 Then
            Exit Sub
        End If

        '------------------------------------------------------------

        ' Give the user the option to run

        ' multiple copies of this application

        '------------------------------------------------------------

        Dim XMsg As String = "A copy of Your Application Name" & _
                             ControlChars.CrLf & _
                             "is already running" & _
                             ControlChars.CrLf & ControlChars.CrLf & _
                             "Continue?"
        If MessageBox.Show(XMsg, _
                           "Copy Running", _
                           MessageBoxButtons.YesNo, _
                           MessageBoxIcon.Question) = DialogResult.No Then
            End
        End If

    End Sub
#End Region

PAR Make Active Window Code

This version of the sub makes the copy of the application that's already running the active window and then ends. Note that the Declare statements must be moved to the form's declarations section.

    Declare Function OpenIcon Lib "user32" (ByVal hwnd As Long) As Long
    Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
#Region " ... OnHandleCreated "
    Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        '------------------------------------------------------------

        '     Date          Developer            Code Change

        '  ---------- -------------------- --------------------------

        '  12/10/2005       G Gilbert            Original code

        '------------------------------------------------------------


        '------------------------------------------------------------

        ' Get all of the active processes for the application

        '------------------------------------------------------------

        Dim CurrentProcesses() As Process
        CurrentProcesses = Process.GetProcessesByName _
                           (Process.GetCurrentProcess.ProcessName)

        '------------------------------------------------------------

        ' If there is no previous copy

        ' of the application running, bail

        '------------------------------------------------------------

        If CurrentProcesses.GetUpperBound(0) <= 0 Then
            Exit Sub
        End If

        '------------------------------------------------------------

        ' Make the prior instance of the application

        ' the active window and terminate this

        ' new instance

        '------------------------------------------------------------

        Dim i As Integer
        Dim Result As Long
        Dim ProcessHandle As Long
        For i = 0 To CurrentProcesses.GetUpperBound(0)
            ProcessHandle = CurrentProcesses(i).MainWindowHandle.ToInt32
            If ProcessHandle <> 0 Then
                '** Restore and activate the copy already running

                Result = OpenIcon(ProcessHandle)
                Result = SetForegroundWindow(ProcessHandle)
            End If
        Next
        End

    End Sub
#End Region

Points of Interest

The End statement is used to terminate the new instance of an application instead of Application.Exit(). The latter statement allows the startup form to load before the program is terminated. This causes a disturbing flash on the screen. With the End statement, the form is not loaded and, thereby, the flash is avoided.

Conclusion

Determining whether or not another instance of an application is running is a function that has been done to death on code exchange sites. Usually, the code will make the previous copy of the application the active window when there is a copy already running. That is an option, however, making the application the active window may not be appropriate for all projects. In addition, other versions of this code I have run across during my research tend to be unnecessarily lengthy. I prefer my versions because they're concise, and, the configurable Double Text library affords me a full range of options for how each new copy of the code I generate will handle the "already running" situation.


Licensing And Limitation Of Liability

You may use the Double Text library and all code offered in this article any way you choose without restriction.

Under no circumstances, and under no legal theory, tort, contract, or otherwise, will George Gilbert (hereafter referred to as "software author") or his licensors, be liable to the user of the Double Text library and all code offered in this article (hereafter referred to collectively as "article code"), for any damages, including any lost profits, lost data, or other indirect, special, incidental or consequential damages, arising out of the use or inability to use the article code, and data or information supplied, even if the software author, his licensors or authorized dealer have been advised of the possibility of such damages, or for any claim by any other party.

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

About the Author

George B Gilbert


Member
Click here to see a complete list of my articles.
Occupation: Software Developer
Company: 2 Good Software
Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
GeneralNice Article Pinmembercomputerguru923826:45 3 Mar '06  
GeneralRe: Nice Article PinmemberGeorge B Gilbert7:34 3 Mar '06  
GeneralRe: Nice Article Pinmembercomputerguru9238210:23 3 Mar '06  
GeneralRe: Nice Article Pinmembercomputerguru923829:13 4 Mar '06  
GeneralRe: Nice Article PinmemberGeorge B Gilbert14:33 4 Mar '06  
GeneralFast user switching Pinmemberjmedved12:36 9 Feb '06  
GeneralRe: Fast user switching PinmemberGeorge B Gilbert16:09 9 Feb '06  
GeneralRe: Fast user switching PinmemberMark Brandon12:14 23 Mar '06  
GeneralRe: Fast user switching PinmemberGeorge B Gilbert18:33 23 Mar '06  
GeneralCode reuse PinmemberChrisVaughan21:29 18 Jan '06  
QuestionDouble text PinmemberHojjats22:06 18 Jan '06  
GeneralRe: Code reuse PinmemberGeorge B Gilbert5:37 19 Jan '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Jan 2006
Editor: Smitha Vijayan
Copyright 2006 by George B Gilbert
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project