Last active
August 29, 2015 13:56
-
-
Save thejustinwalsh/8981811 to your computer and use it in GitHub Desktop.
Class to handle the case where you need a single instance of an application
This file contains hidden or 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.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
/* Usage: | |
/////////////////////////////////////////////////////////////// | |
static void Main (string[] args) | |
{ | |
if (!SingleInstance.CreateInstance()) { return; } | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(new FormMain()); | |
SingleInstance.DestroyInstance(); | |
} | |
*/ | |
namespace App.Utils | |
{ | |
static class SingleInstance | |
{ | |
static private Mutex mutex; | |
static private string AssemblyGuid | |
{ | |
get | |
{ | |
object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false); | |
if (attributes.Length == 0) | |
{ | |
return String.Empty; | |
} | |
return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value; | |
} | |
} | |
static public bool CreateInstance() | |
{ | |
bool onlyInstance = false; | |
string mutexName = String.Format("Local\\{0}", SingleInstance.AssemblyGuid); | |
mutex = new Mutex(true, mutexName, out onlyInstance); | |
return onlyInstance; | |
} | |
static public void DestroyInstance() | |
{ | |
mutex.ReleaseMutex(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment