Click here to Skip to main content
15,884,537 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.
2.50/5 (3 votes)
29 Mar 2011CPOL 13K   2   4
I actually use code like this, which allows me to detect a existing instance and to call the original instance with the command line (I expand any filenames present so that it can access the filenames even if the original path is different).string processName =...
I actually use code like this, which allows me to detect a existing instance and to call the original instance with the command line (I expand any filenames present so that it can access the filenames even if the original path is different).
C#
string processName = Process.GetCurrentProcess().ProcessName;
Process[] instances = Process.GetProcessesByName(processName);

if (instances.Length > 1)
{
    //Try and send a message with args[]
    StringBuilder text = new StringBuilder();
    foreach (string str in args)
    {
        if (File.Exists(str))   //If it is a file, I want full path
        {
            text.Append(new FileInfo(str).FullName);
        }
        else
        {
            text.Append(str);
        }
        text.Append(' ');
    }
    if (text.Length > 0)
    {
        text.Remove(text.Length - 1, 1);
    }
    Remote.Send(text.ToString());
    // MessageBox.Show("This application is already running");
    return;
}


The Remote class is available here. Simple Interprocess Communication[^]

License

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


Written By
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 1 reason for my vote of 1. I don't see... Pin
charles henington13-Apr-11 3:25
charles henington13-Apr-11 3:25 
GeneralRe: The code is in Main before you do App app = new App(); app.R... Pin
Neil A. Harding13-Apr-11 6:03
Neil A. Harding13-Apr-11 6:03 
GeneralWould you mind telling us what "Remote" refers to in your co... Pin
loyal ginger29-Mar-11 3:48
loyal ginger29-Mar-11 3:48 
GeneralBe aware that this Code won't work in Terminal Server Sessio... Pin
Nenad L.22-Mar-11 3:10
Nenad L.22-Mar-11 3:10 

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.