Created
August 5, 2014 08:26
-
-
Save AlexArchive/1726b2a7a25620a53219 to your computer and use it in GitHub Desktop.
Limit your Windows Forms application to a single instance (run once).
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
using System; | |
using System.Reflection; | |
using System.Runtime.InteropServices; | |
using System.Threading; | |
using System.Windows.Forms; | |
namespace Screenshot | |
{ | |
public static class StartupController | |
{ | |
private static Mutex _mutex; | |
public static void RunOnce<TForm>() where TForm : Form | |
{ | |
_mutex = new Mutex(false, GenerateMutexName()); | |
if (MutexHandleIsObtainable()) | |
{ | |
Run<TForm>(); | |
return; | |
} | |
Environment.Exit(1); | |
} | |
public static void Run<TForm>() where TForm : Form | |
{ | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(Activator.CreateInstance<TForm>()); | |
} | |
private static bool MutexHandleIsObtainable() | |
{ | |
try | |
{ | |
return _mutex.WaitOne(TimeSpan.Zero, false); | |
} | |
catch (AbandonedMutexException) | |
{ | |
return true; | |
} | |
} | |
private static string GenerateMutexName() | |
{ | |
return string.Format("Global\\{{{0}}}", ResolveAssemblyGuid()); | |
} | |
private static string ResolveAssemblyGuid() | |
{ | |
try | |
{ | |
var assembly = Assembly.GetExecutingAssembly(); | |
var assemblyAttributes = assembly.GetCustomAttributes(typeof (GuidAttribute), false); | |
var guidAttribute = (GuidAttribute) assemblyAttributes.GetValue(0); | |
return guidAttribute.Value; | |
} | |
catch | |
{ | |
throw new InvalidOperationException( | |
"You must ensure that a Guid attribute has been defined for this assembly."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment