Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 911
Usman Avatar asked Jun 28 '11 16:06

Usman


2 Answers

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.

like image 60
Phil Wright Avatar answered Nov 04 '22 03:11

Phil Wright


This is due to the fact that the function you are calling "Control.FromHandle" uses a hash table to lookup the control instance from it's handle. So when you call this method for an HWND that does not have a control instance you will get null.

To use an HWND you should use the Win32 Messaging API via PInvoke calls. For instance, You can use SendMessage to send a WM_GETTEXT message to query the window's text. For some of these messages there are various wrappers in the Win32 Windowing API like GetWindowText which wrap the above message.

like image 31
csharptest.net Avatar answered Nov 04 '22 05:11

csharptest.net