Previnstance function

T

Tom Edelbrok

In the VB.Net documentation it says that there is no direct equivalent to
VB6's 'PrevInstance' function, so they suggest making your own with the
following code:

Function PrevInstance() As Boolean

If
(UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName))

Return True

Else

Return False

End If

End Function



The only problem is that the VB.NET documentation qualifies this with the
comment that "once a second instance is loaded, the first instance will also
return true". For example, as soon as a second app is opened while the first
is already open, I can force the new app instance to close. But ever after
that I get a value of TRUE back, even if one of our users is trying to open
the application after having gone through a situation where they opened it
twice. I end up having to get the user to log out and back in again to reset
the process count.

Is there a better way to detect and kill duplicate app instances? Where is
the process count stored ... in the registry? (Can I reset it from in the
program when I close a duplicate instance)?



Thanks for help in advance,



Tom
 
C

Crouchie1998

Here's one way, but it doesn't seem to work with VB.NET 2002 in case you
have it

Public Function PrevInstance() As Boolean
If
UBound(System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Proc
ess.GetCurrentProcess.ProcessName)) > 0 Then
Return True
Else
Return False
End If
End Function

Crouchie1998
BA (HONS) MCP MCSE
Official Microsoft Beta Tester
 
A

Adam Goossens

Hi Tom,

There is an alternate method which involves having your application
attempt to hold a uniquely named Mutex on startup.

If you cannot hold the mutex, it means that another instance of your
application has already taken hold of it (and thus another copy is running).

http://www.codeproject.com/managedcpp/mcppsingleinst.asp

Have a look at that article. It's written in Managed C++, but you can
take the concept and apply it to VB.NET

If you don't know C++, here's an example:

---
Imports System.Threading

'...
Dim mut as Mutex
mut = New Mutex(false, "InsertYourUniqueStringHere")

If Not mut.WaitOne(1, true) Then
' application is already running
' (WaitOne returns FALSE if we can't get the lock)
MessageBox.Show("Another instance of this application is already
running.")

Application.Exit() ' if you're in Windows Forms
End If
'...
---

Just *make sure* you free the mutex before you end your application!

BTW: It might be a good idea to generate and use a GUID as your unique
string.

Regards,
-Adam.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top