A singelton application is an application which only allows running one instance of itself per machine. e.g. Microsoft Outlook is a singelton application. Everytime the user starts the application it will check if an instance is already running. If its not running it will launch it otherwise it will focus to the current one. Here is the source of how to create a singelton application with C# and .net …
- using System.Threading;
- //Allows to run the application only once per machine
- public static class SingeltonApplication {
- static Mutex _mutex;
- public static void Run(Form form) {
- if (IsFirstInstance()) {
- Application.ApplicationExit += OnExit;
- Application.Run(mainForm);
- }
- }
- public bool IsFirstInstance() {
- Assembly a = Assembly.GetEntyAssembly();
- _mutex = new Mutex(false, a.FullName);
- bool owned = false;
- owned = _mutex.WaitOne(TimeSpan.Zero, false);
- return owned;
- }
- static void OnExit(object sender, EventArgs args) {
- _mutex.ReleaseMutex();
- _mutex.Close();
- }
- }
The trick here is to get a cross-process communication because every application runs in its own process. This is achieved with a Mutex which is available system wide. We use the name of the application for the identification of the Mutex.
the source is inspired from the book “.net Components, Juval Löwy, O’Reilly United States” page 231