There is another better way to achieve this. We can use Mutex object in System.Threading namespace for this purpose. Here you go for the sample code.
namespace My_Samples { using System; using System.Threading; class Program { static Mutex mutex; static void Main(string[] args) { string appName = "My Application"; bool createdNew; bool initiallyOwned = true; mutex = new Mutex(initiallyOwned, appName, out createdNew); if (!createdNew) { System.Environment.Exit(0); } Console.WriteLine("Application Is Running..."); Console.ReadLine(); } } }
The overloaded Mutex class converter takes 3 parameters
initiallyOwned - true to give the calling thread initial ownership of the named system mutex
appName – Current application name
createdNew –This is an Boolean out parameter which indicates whether the mutex is already created or not.
Here I just provided a Console sample; you may use the same in Winform or WPF applications with minor tweaking.
No comments:
Post a Comment