Last active
December 18, 2015 00:19
-
-
Save AlexArchive/5696093 to your computer and use it in GitHub Desktop.
Single Instance Startup Controller for Windows Forms Applications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//<sumary> | |
//Sample Usage of the StartupController class | |
//</sumary> | |
static class Program | |
{ | |
[STAThread] | |
static void Main() | |
{ | |
StartupController startupController = new StartupController(); | |
startupController.RunOnce<MainForm>(); | |
} | |
} | |
internal class StartupController | |
{ | |
private Mutex _globalMutex; | |
public void RunOnce<T>() where T : Form | |
{ | |
InitializeMutex(); | |
bool isNotAlreadyRunning = CanObtainMutexHandle(); | |
if (isNotAlreadyRunning) | |
{ | |
Run<T>(); | |
} | |
else | |
{ | |
Environment.Exit(0); | |
} | |
} | |
public void Run<T>() where T : Form | |
{ | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(Activator.CreateInstance<T>()); | |
} | |
private void InitializeMutex() | |
{ | |
MutexSecurity accessControl = new MutexSecurity(); | |
SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null); | |
MutexAccessRule accessRule = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow); | |
accessControl.AddAccessRule(accessRule); | |
_globalMutex = new Mutex(false, ResolveMutexIdentifier()); | |
_globalMutex.SetAccessControl(accessControl); | |
} | |
private bool CanObtainMutexHandle() | |
{ | |
try | |
{ | |
return _globalMutex.WaitOne(TimeSpan.Zero, false); | |
} | |
catch (AbandonedMutexException) | |
{ | |
return true; | |
} | |
} | |
private static string ResolveGuid() | |
{ | |
var assemblyAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false); | |
var guidAttribute = assemblyAttributes.GetValue(0) as GuidAttribute; | |
if (guidAttribute == null) | |
throw new InvalidOperationException("Failed to resolve GUID"); | |
return guidAttribute.Value; | |
} | |
private static string ResolveMutexIdentifier() | |
{ | |
return string.Format("Global\\{{{0}}}", ResolveGuid()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment