I have restricted my C# windows application to only allow one instance to be running at a time, using this question How to force C# .net app to run only one instance in Windows?
It works well and does not allow more than one instance of the application to run at the same time.
The problem is that if the user attempts to open a second instance of the application, I want the currently active one to come to the front.
The question I worked from seems to address this, but it is not working for me.
I think it is because my application is not meeting the criteria to allow the method :SetForegroundWindow
to work.
My question is, how can I achieve this. My code is below:
using System ;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace RTRFIDListener_Client
{
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "RTRFIDListener_Client", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frm_Main());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
}
}