If you are using InnoSetup for your installation needs you might be familiar with AppMutex parameter. You just give it SomeUniqueValue and make sure that Mutex with same value is created within your application. That way setup will warn you if your application is already running. Useful function indeed.
Simplest way to implement this would be:
static class App {
private static Mutex SetupMutex;
[STAThread]
static void Main() {
using (var setupMutex = new Mutex(false, @"Global\SomeUniqueValue")) {
...
Application.Run(myForm);
}
}
}
And this code will work if you deal with single user. In multi-user environment this will throw UnauthorizedAccessException. Why? Because Mutex is created within current user security context by default. To have behavior where any instance, no matter which user, will keep our Mutex alive, we need to adjust security a little.
Since making null security descriptor in .NET is real pain, we can do next best thing - give everybody an access. With slightly more code we can cover multi-user scenario.
static class App {
static void Main() {
bool createdNew;
var mutexSec = new MutexSecurity();
mutexSec.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
MutexRights.FullControl,
AccessControlType.Allow));
using (var setupMutex = new Mutex(false, @"Global\SomeUniqueValue", out createdNew, mutexSec)) {
...
Application.Run(myForm);
}
}
}
P.S. No, giving full access to mutex that is used purely for this purpose is not a security hole…