The following code implements a simple singleton that allows you to run only one instance of my application. However, if another instance starts up, I need to be able to capture the command line arguments of that instance, pass them to the original instance, and then complete the second instance.
The problem occurs when I try to get the first instance of the application. As soon as I found the handle to the main form of this instance, I pass it to the method Control.FromHandle(), expecting to return MainForm. Instead, the return value is always null. ( Control.FromChildHandle()gives the same result.)
So my question is simple: what am I doing wrong? And is this even possible in .NET?
public class MainForm : Form
{
[DllImport("user32")]
extern static int ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32")]
extern static bool SetForegroundWindow(IntPtr hWnd);
private Mutex singletonMutex;
private void MainForm_Load(object sender, EventArgs e)
{
bool wasCreated;
singletonMutex = new Mutex(false, Application.ProductName + "Mutex", out wasCreated);
if (!wasCreated)
{
Process thisProcess = Process.GetCurrentProcess();
Process[] peerProcesses = Process.GetProcessesByName(thisProcess.ProcessName.Replace(".vshost", string.Empty));
foreach (Process currentProcess in peerProcesses)
{
if (currentProcess.Handle != thisProcess.Handle)
{
ShowWindowAsync(currentProcess.MainWindowHandle, 1);
SetForegroundWindow(currentProcess.MainWindowHandle);
MainForm runningForm = (MainForm) Control.FromHandle(currentProcess.MainWindowHandle);
if (runningForm != null)
{
runningForm.Arguments = this.Arguments;
runningForm.ProcessArguments();
}
break;
}
}
Application.Exit();
return;
}
}