The Most Active and Friendliest
Affiliate Marketing Community Online!

“Adavice”/  “1Win

Sample C# code for single instance of applications

Kleopatra

New Member
affiliate
Ever wanted to only allow a single instance of your application to be run at a time? If so, read on ....

There are many ways to check for instances, but I have found that the easiest (not necessarily the most robust, however) is using a Mutex.

I am using the MS VCSExpress IDE so a lot of background stuff (which is not included in
this snippet) is done automatically.

The following code assumes you also have a class created for Form1.

Code:
using System;using System.Collections.Generic;using System.Windows.Forms;using System.Threading;namespace WindowsApplication1{ static class Program { // this must be declared static since the class is static private static Mutex m; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); bool ok; //The name used when creating the mutex can be any string you want m = new Mutex(true, "MyApp", out ok); if (!ok) { MessageBox.Show("Application Already Running"); return; } // This starts the message loop and opens the intial Form Application.Run(new Form1()); // The next line is important so the garbage collector (GC) // doesn't collect the mutex before your done with it GC.KeepAlive(m); } }}
Many of the coders here probably already knew this, but it might come in handy for some of those new to programming.

If anyone has any questions or would like other code snippets, just reply to this thread.
 
MI
Back