I have a winforms Application,
On Close button click, I am hiding that application into system tray just like how skype works..
If the application is instantiated again and if an instance of that application is already running, then I want to bring the already running application(may be in tray) to front and exit the new one..
What I thought of doing is something like this in the Main mathod using the WCF
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcesses();
bool running = false;
foreach (var process in processes)
{
if (process.ProcessName == currentProcess.ProcessName
&& process.Id != currentProcess.Id)
{
running = true;
}
}
if (running)
{
ChannelFactory<IService1> pipeFactory = new
ChannelFactory<IService1>(new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/PipeActivate"));
IService1 pipeProxy = pipeFactory.CreateChannel();
pipeProxy.ActivateThisWindow();
Application.Exit();
}
else
{
using (ServiceHost host = new
ServiceHost(typeof(Form1),
new Uri[] { new Uri("net.pipe://localhost") }))
{
host.AddServiceEndpoint(typeof(IService1),
new NetNamedPipeBinding(), "PipeActivate");
host.Open();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
host.Close();
}
}
where
void IService1.ActivateThisWindow()
{
this.Show();
if (this.WindowState != FormWindowState.Normal)
this.WindowState = FormWindowState.Normal;
this.Activate();
}
now the problem is, its bringing the running instance to front but as the new instance exits, its going to its previous state.
What is the problem? How can I solve this?
what other ways I can use to achieve this requirement?
While this is a very novel approach, it is kind of overkill. There is an easier and more widely used way to handle this problem as seen here.
What is the correct way to create a single-instance application?
Speaking from personal experience, I used this resource for all of my single instance apps, and it works like a charm.