Click here to Skip to main content
15,890,670 members
Articles / Programming Languages / C#
Tip/Trick

Allow only one instance of a c# application

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
2 Mar 2010CPOL 12.3K   4  
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.///...
MSIL
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();

}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
South Africa South Africa
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
-- There are no messages in this forum --