Considering that:
Application instance "A" running.
Open a new instance "B".
Instance "B" checks if another instance is already running.
Positive result, "A" is running.
Exit instance "B".
You want the instance "A" to be placed in the foreground or to restore the window if it is minimized before closing the "B" instance.
As instance "B" has no control over instance "A", and "A" does not know the attempt to open "B", you need to use the Windows API so that instance "B" can bring A forward.
Example 1:
static class Program
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
[System.STAThread]
static void Main()
{
if (_mutex.WaitOne(System.TimeSpan.Zero, true))
{
try
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new Programa());
}
finally { _mutex.ReleaseMutex(); }
}
else
{
System.Windows.Forms.MessageBox.Show("Já existe um Gerador de Deck aberto.", "Gerador de Deck", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(p.ProcessName);
foreach (System.Diagnostics.Process pp in ps)
{
if (pp.Id != p.Id)
{
Program.SwitchToThisWindow(pp.MainWindowHandle, true);
}
}
}
}
}
Example 2:
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[System.STAThread]
static void Main()
{
if (_mutex.WaitOne(System.TimeSpan.Zero, true))
{
try
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new Programa());
}
finally { _mutex.ReleaseMutex(); }
}
else
{
System.Windows.Forms.MessageBox.Show("Já existe um Gerador de Deck aberto.", "Gerador de Deck", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(p.ProcessName);
foreach (System.Diagnostics.Process pp in ps)
{
if (pp.Id != p.Id)
{
Program.SetForegroundWindow(pp.MainWindowHandle);
}
}
}
}
}
Sorry if you were a bit confused by these "A" / "B's", lol
the first example, is how I used it.
The second, I found here: link
There is a detail that you test if there is another instance by the GUID, while to get the MainWindowHandle
we need the name of the process. The function will not work if the second instance is a copy of the executable with another name.
Details about the functions SetForegroundWindow
and SwitchToThisWindow
: link
I hope it helps.