Skip to content

Instantly share code, notes, and snippets.

@meziantou
Last active May 22, 2022 13:41
Show Gist options
  • Save meziantou/84b46cee16e9b565675e to your computer and use it in GitHub Desktop.
Save meziantou/84b46cee16e9b565675e to your computer and use it in GitHub Desktop.
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