views:

100

answers:

1

Hello, I would like to limit an application to having only one instance running on a machine. So far I have this :

Mutex m = new Mutex(true, Name, out IsOwned);

if (!IsOwned)
{
    string message = "There is already a copy of the application '" +
        Name + 
        "' running. Please close that application before starting a new one.";

    MessageBox.Show(message, "Error", 
        MessageBoxButtons.OK, MessageBoxIcon.Information);

    Environment.Exit(0);
}
else
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

And it exits, but is there a way to maximise the first instance before this one closes?

+2  A: 

This isn't the way you want to handle multiple instances of the application. The accepted practice is to just switch to the running instance of the application.

That being said, you can easily create a class that derives from WindowsFormsApplicationBase (in the Microsoft.VisualBasic namespace). This answer outlines how you would do it, and indicate that you want a single instance, as well as how to handle what happens when you try and run a new instance:

http://stackoverflow.com/questions/424368/opening-a-known-file-type-into-running-instance-of-custom-app-net/424390#424390

casperOne