65.9K
CodeProject is changing. Read more.
Home

Run Only One Copy Of Application

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (3 votes)

Mar 21, 2011

CPOL
viewsIcon

13947

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).
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[^]