Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SingleInstance
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
namespace SingleInstance
{
class Program
{
const string AppId = "Local\\1DDFB948-19F1-417C-903D-BE05335DB8A4";
static void Main(string[] args)
{
using (Mutex mutex = new Mutex(false, AppId))
{
if (!mutex.WaitOne(0))
{
// Another instance is already started
try
{
IpcChannel channel = new IpcChannel();
ChannelServices.RegisterChannel(channel, false);
SingleInstance app = (SingleInstance)Activator.GetObject(typeof(SingleInstance), string.Format("ipc://{0}/RemotingServer", AppId));
app.Execute(args);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return;
}
RegisterIpcServer();
Console.WriteLine("Started");
Console.ReadKey();
}
}
private static void RegisterIpcServer()
{
IpcChannel channel = new IpcChannel(AppId);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingleInstance), "RemotingServer", WellKnownObjectMode.Singleton);
}
private class SingleInstance : MarshalByRefObject
{
public void Execute(string[] args)
{
Console.WriteLine("Second instance: " + string.Join(" ", args));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.