Click here to Skip to main content
15,887,240 members
Articles / Desktop Programming / Windows Forms
Alternative
Tip/Trick

Run Only One Copy Of Application

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
30 Mar 2011CPOL 9.4K   4   5
Just because we like C# doesn't mean we can't borrow from other .NET languages. I've always had good luck and less complication using VB's single instance methodology in my C# applications. This code would go in your program.cs file:/// /// We inherit from...
Just because we like C# doesn't mean we can't borrow from other .NET languages. I've always had good luck and less complication using VB's single instance methodology in my C# applications. This code would go in your program.cs file:
C#
/// <summary>
///  We inherit from WindowsFormApplicationBase which contains
///  the logic for the application model, including
///  the single-instance functionality.
/// </summary>
public class App : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
    #region Constructors

    public App()
    {
        this.IsSingleInstance = true; // makes this a single-instance app
        // C# windowsForms apps typically turn this on.  We'll do the same thing here.
        this.EnableVisualStyles = true;
        // the vb app model supports two different shutdown styles.
        // We'll use this one for the sample.
        this.ShutdownStyle = 
         Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses;
    }

    #endregion Constructors

    #region Methods

    /// <summary>
    /// This is how the application model learns what the main form is
    /// </summary>
    protected override void OnCreateMainForm()
    {
        this.MainForm = Program.MainForm;
    }

    /// <summary>
    /// Gets called when subsequent application launches occur.
    /// The subsequent app launch will result in this function getting called
    /// and then the subsequent instances will just exit.
    ///  You might use this method to open the requested doc, or whatever
    /// </summary>
    /// <param name="eventArgs"></param>
    protected override void OnStartupNextInstance(
       Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
    {
        base.OnStartupNextInstance(eventArgs);
        //System.Windows.Forms.MessageBox.Show("An attempt to launch another instance of this app was made");
    }

    #endregion Methods
}

public static class Program
{
    #region Fields
    public static string[] CommandLine;
    public static Form1 MainForm = new Form1();
    public static App myApp = new App();
    #endregion Fields

    #region Events
    #endregion Events

    #region Properties
    #endregion Properties

    #region Methods


    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThreadAttribute]
    static void Main(string[] commandLine)
    {
        // The one and only "Main" method of an application.
        // This is what runs when you launch the application
        // Everything else is a result of what happens here

        CommandLine = commandLine;
        Control.CheckForIllegalCrossThreadCalls = false;
        Application.EnableVisualStyles();

        // Do whatever preparation you like... load settings... whatever

        // Now that we *finally* have everything set up, let's run one instance of our App
        try
        {
            string cmdls = string.Empty;
            foreach (var s in commandLine)
            {
                cmdls += s + "\n";
            }
            myApp.Run(commandLine);
        }
        catch (Exception err)
        {
            Console.WriteLine(err.Message, "Main");
        }
    }

    #endregion Methods
}

License

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


Written By
Software Developer http://stlaurent.me
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 2 Most usefull for me Pin
Moahmedkaz9-May-11 19:00
Moahmedkaz9-May-11 19:00 
GeneralReason for my vote of 4 nice not a fan of vb but a 4 none th... Pin
charles henington22-Apr-11 6:08
charles henington22-Apr-11 6:08 
Generalhmmm - I don't like Control.CheckForIllegalCrossThreadCalls ... Pin
johannesnestler3-Apr-11 10:26
johannesnestler3-Apr-11 10:26 
GeneralRe: It really doesn't make a differnce the Control.CheckForIlleg... Pin
charles henington19-Apr-11 11:38
charles henington19-Apr-11 11:38 
GeneralThe main problem with this approach is that it uses Remoting... Pin
Phil J Pearson2-Apr-11 10:20
Phil J Pearson2-Apr-11 10:20 
The main problem with this approach is that it uses Remoting (over which the programmer has no control). That can seriously mess up any Remoting you want to do yourself.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.