Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created August 5, 2014 08:26
Show Gist options
  • Save AlexArchive/1726b2a7a25620a53219 to your computer and use it in GitHub Desktop.
Save AlexArchive/1726b2a7a25620a53219 to your computer and use it in GitHub Desktop.
Limit your Windows Forms application to a single instance (run once).
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