How to get an instance of System.Windows.Form from its Win32 descriptor?

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);

  // returns false for every instance except the first
  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); // SW_NORMAL
        SetForegroundWindow(currentProcess.MainWindowHandle);

        // always returns null !!!
        MainForm runningForm = (MainForm) Control.FromHandle(currentProcess.MainWindowHandle);

        if (runningForm != null)
        {
          runningForm.Arguments = this.Arguments;
          runningForm.ProcessArguments();
        }

        break;
      }
    }

    Application.Exit();

    return;
  }
}
+5
6

.NET. , , .

+4

Control.FromHandle , , , (, , ).

WindowHandle, Win32 API. WinForms .

(WM_) , .

  • - .

  • (WCF)

+3

var form = (Form)(Control.FromHandle(myHandle));

, . . .

- Remoting. , , -, , .

+2

,

, , ( WinAPI PostMessage WndProc), , .net

0

Microsoft.VisualBasic.dll, , nobugz. , #. OnStartupNextInstance , .

, .

0

All Articles