65.9K
CodeProject is changing. Read more.
Home

Allow only one instance of a c# application

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 3, 2010

CPOL
viewsIcon

12521

This code creates a mutex before starting an application and releases the mutex when the application is closed. A user will only be able to start the application once. This can be used for services as well./// /// The main entry point for the application.///...

This code creates a mutex before starting an application and releases the mutex when the application is closed. A user will only be able to start the application once. This can be used for services as well.

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

public static void Main()

{

bool createdMutex = true;

Mutex mutex = new Mutex(true, "ConfigureApp", out createdMutex);

if (createdMutex && mutex.WaitOne())

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new MainForm());

mutex.ReleaseMutex();

}

else

{

MessageBox.Show("Only one application instance is allowed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

mutex.Close();

}