views:

155

answers:

0

In our SDK (DotNET SDK for an unmanaged C++ application) we offer a way for plug-in developers to get the main window of our application.

public static System.Windows.Forms.NativeWindow MainWindow()
{
  System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
  if( null==process )
    return null;
  IntPtr handle = process.MainWindowHandle;
  if( IntPtr.Zero==handle )
    return null;
  return System.Windows.Forms.NativeWindow.FromHandle(handle);
}

It all seems to work fine, but the NativeWindow.FromHandle() returns null. Any ideas why this should be happening? I've read the MSDN remark section and I've looked at the method using Reflector, but I don't see where the mistake could be.

The process instance is correctly pointing at the unmanaged process, and the handle appears to be correct as well.


Edit:

This seems to work:

public static System.Windows.Forms.NativeWindow MainWindow()
{
  System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
  if( null==process )
    return null;
  IntPtr handle = process.MainWindowHandle;
  if( IntPtr.Zero==handle )
    return null;

  System.Windows.Forms.NativeWindow wnd = System.Windows.Forms.NativeWindow.FromHandle(handle);
  if (wnd == null) 
  {
    wnd = new System.Windows.Forms.NativeWindow();
    wnd.AssignHandle(handle);
  }

  return wnd;
}