Single instance of an app

G

Guest

I'd like to prevent my app from running more than once. In VB6 this was
simple using PrevInstance. MSDN Library describes using
Diagnostics.Process.GetProcessByName to see if the the currently running
thread has another instance running. Works great as Adminstrator but throws
a SecurityPermission exception when run from a Windows account that only
belongs to BUILTIN\Users.

Is there a simple way to do this?
 
B

Brian P. Hammer

Here's what I use....

Dim m As Mutex
Dim first As Boolean
m = New Mutex(True, CN.gstrcAppTitle, first)
If Not (first) Then
'run your shutdown code here
Exit Sub
End If

HTH,
Brian
 
J

Jon Skeet [C# MVP]

Brian P. Hammer said:
Here's what I use....

Dim m As Mutex
Dim first As Boolean
m = New Mutex(True, CN.gstrcAppTitle, first)
If Not (first) Then
'run your shutdown code here
Exit Sub
End If

That might fail in release mode - unless you reference the mutex later
on, it can be garbage collected after creation, allowing a second
instance to be created and think it's the first. You should either make
the mutex a static (shared) variable, or use GC.KeepAlive, or in C# my
favourite solution is:

using (Mutex m = ....)
{
// Do main application stuff here
}
 
B

Brian P. Hammer

Jon - You are correct - In my typing, I dimed instead of static declared.
Thanks for pointing it out.

Brian
 

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