On The Insider: Nikki Blonsky 'Living in Pain'

Make only one instance of an application run with VB.NET

Tags: Microsoft development tools, Programming languages, Irina Medvinskaya, Microsoft Visual Basic.Net, strModName, strProcName, appProc, Visual Basic Tips Newsletter

  • Save
  • Print
  • 1

Takeaway: Irina Medvinskaya presents a way to allow only one instance of an application run with VB.NET. She presents a code example that uses the System.Diagnostics.Process class to determine whether there is more than one instance of an application running.

It's usually a good practice to make sure that only one instance of your application can be run at a time. In order to determine if there are other instances of an application running, you need to get a list of all the processes running and see if an instance of the application is there. In Listing A, I utilize the System.Diagnostics.Process class for this purpose.

In the example, I define an array, appProc, as a Process. Then I define two string variables: strModName and strProcName. The value of variable strModName is set to the Process.GetCurrentProcess.MainModule.ModuleName property, and the value of variable strProcName is set to the System.IO.Path.GetFileNameWithoutExtension, to which I pass the name of the module in strModName. I set the value of the array appProc to the value of Process.GetProcessesByName and pass the strProcName to it. Then, I simply check the Length property of the array appProc. If the length is more than one, it means that there is more then one instance of the application running, which is what I use to base the displayed message box on.

Notes about the example

You should use the example as a part of the Main routine of an application. If you determine that there are other instances of this application running, you can decide on the appropriate action; in most cases, alerting a user to the fact that the application is already running will be enough. If there are no other instances of the application running, you can proceed with the necessary application logic.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

  • Save
  • Print
  • 1

Print/View all Posts Comments on this article

Where is the codedjj55  | 10/27/06
VS2005 does this automagicallyJustin James  | 10/27/06
Not available in console programjleather  | 10/27/06
Good Point/More SuggestionsJustin James  | 10/27/06
Making the running instance activeBF.NET  | 10/27/06
Try this . . .jleather  | 10/30/06
Code sample is listedAndy M  | 10/27/06
Thanksdjj55  | 10/27/06
Here's how to do it in VB6ChuckSomerville  | 10/27/06
RE: Not Vista Compatable?wcarlson@...  | 03/04/08
ANSWEREDwcarlson@...  | 03/11/08

What do you think?

advertisement
Click Here