Why Control.FromHandle(IntPtr) returns null in one hooked process and returns valid object of "Form"? in another hooked process?

Usman picture Usman · Jun 28, 2011 · Viewed 8.7k times · Source

I am facing a problem related to get out all the controls from some hooked process. My SpyDll launched into hooked process sucessfully, But when I check the statement

Control control = Control.FromHandle(MainWindowHandle), it returns null into control object where "MainWindowhandle"is just a native main window handle of that hooked process, which you always take from .NET "Process" class after launching that process.

But STRANGLY it happens that in some other hooked process which is the same C# .NET application, it returns valid object of Main "WinForm".

So why it will not work in above case? Are there any exceptions to use "MainWindowHandle" properly. In my case both are seperate .NET managed processes programmed in C#. Any process configuration needs to maintain specially while creating that process?

Regards Usman

Answer

Phil Wright picture Phil Wright · Jun 29, 2011

When you create a Control/Form using WinForms the WinForm code will automatically keep an entry that maps the native window handle to the C# instance. When the Control/Form is destroyed that entry is then removed. So all calling Control.FromChildHandle does is search the list of entries to see if it has a matching native handle and if so returns the associated C# instance.

Therefore you will only get back C# entries for Control/Form instances created from WinForms itself. Native windows and native control from attaching to another process will never return an entry. That is why is does not work for you and never will and also why you get back a valid class when working with a C# application which has used WinForms to create the window.