Getting a Control from an HWND.

  • Thread starter Thread starter Joe Coplen
  • Start date Start date
J

Joe Coplen

I'm trying to build a GUI automation tool to test a VS.Net add-in. To do
this, I want to be able to walk the window hierarchy starting at the app's
main window. Is there a way to get a System.Windows.Forms.Control from an
HWND? I've tried calling Control.FromHandle(HWND) and it always returns
null. I can't get NativeWindow.FromHandle(HWND) to return anything but null
either.

I'm getting the window handle to the VS7 IDE using FindWindow, which I'm
importing from User32.dll:

[DllImport("user32.dll", SetLastError=true)]
private static extern IntPtr FindWindow(string lpClassName, string
lpWindowName);

I start VS7 here:

System.Diagnostics.Process xProcess =
System.Diagnostics.Process.Start(@"C:\Program Files\Microsoft Visual Studio
..NET\Common7\IDE\devenv.exe");
xProcess.WaitForInputIdle();
xHWND = FindWindow("wndclass_desked_gsk", xProcess.MainWindowTitle);

Once I've got xHWND, it's a valid handle and I can manipulate it (minimize,
maximize, enumerate child windows, etc.) with other imported functions from
User32.dll, but if I give it to System.Windows.Forms.Control.FromHandle(), I
get null back. If I give it to
System.Windows.Forms.NativeWindow.FromHandle() I get null back. Is there a
way to do this at all? I'm in the process of building my own classes for
Win32 windowing because I can't seem to get the native .Net implementation
to work. Does it not work intentionally, or is there something more I need
to do?

-J
 
Joe,
Is there a way to get a System.Windows.Forms.Control from an HWND?

Not with a window hande from another process, no. It only works for
handles that were originally created by a Control object in your app.

I can't get NativeWindow.FromHandle(HWND) to return anything but null
either.

NativeWindow.AssignHandle() should work.



Mattias
 
Back
Top