开发者

WinForms: Form.FromHandle returns null for process main form for code loaded into .net executable

I have a legacy application written in .Net. No sources available. It uses vb scripting to extend it inner logic via events handling. So it's a mix of com and .net.

I used SpyUI app and observed that UI is written with Windows Forms. Controls are titled in .Net style开发者_如何学编程 & it looks like windows forms one (vc++ and vb UI looks completely different).

I want to extend application UI by achieving System.Windows.Forms.Form instance for the main form and modify controls tree.

So i write code in vb script that creates my com object, something like:

Set obj = CreateObject("MyUiExtender")
obj.InjectIntoUi()

I try to get the main form handle for the process object was loaded into and this code works:

Process.GetCurrentProcess().MainWindowHandle; // a meaningfull value
Process.GetCurrentProcess().MainWindowTitle; // the title of the application 

So far so good, but the following doesn't work -> it returns null

var mainForm = Control.FromHandle(Process.GetCurrentProcess().MainWindowHandle)

My object was loaded into executable and I try to get form instance for the same process. I suppose it's a kind of app boundaries problem. My code work perfect if my com object is loaded into .net app via

t = Type.GetTypeFromProgID("MyUiExtender")
dynamic c = Activator.CreateInstance(t)
c.InjectIntoUi();

I suppose using vb scripting ruins application boundaries somehow...

Is it still possible to get main application form instance as an instance of Windows.Forms.Form class ?


The problem is that Control.FromHandle works only for the current process. If you want to get the main form of another .Net process you have to inject your code into other process.

There are few approaches for that. The most common one is to use CreateRemoteThread to load unmanaged dll into other process address space and then load .NET assembly. To make it possible you have to use C++ managed.

If you are the beginner I would recommend using existing library. Have a look at Hawkeye project at CodePlex: http://hawkeye.codeplex.com/ You can find a ready library there.

You can also have a look at http://smuxplugins.codeplex.com/ This is yet another example of the .net code injection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜