如何在我的应用程序中创建的窗体上托管在不同 AppDomain 中创建的 WinForms Control
(或 WPF Window
)?
我正在尝试创建一个复合 UI 应用程序,它是一个无特色的插件外壳/主机,其中这些插件完全在它们自己的应用程序域中运行,所以我希望能够从这些插件中获取 UserControl 对象是“在主机进程的主窗体上的某种容器控件中托管”。
我以为我已经破解了它,但是因为应用程序域之间的对话涉及 MarshallByRefObject 代理,所以我不能采用我的第一个原型(prototype)方法:
shellForm.Panel1.Controls.Add(proxyObjectForUserControlInOtherAssembly);
我已经在问题的末尾发布了我从中得到的异常。
我确实尝试过直接获取控件:
var ctl = Control.FromHandle(proxyObjectForUserControlInOtherAssembly.Handle);
shellForm.Panel1.Controls.Add(ctl);
这给出了可预测的结果。我得到了 hWnd,但是 Control.FromHandle()
返回了 null。大概是因为句柄是在不同的应用程序域上创建的。
如果我无可救药地偏离了轨道,我将非常感谢在正确方向上戳一下。 :)
非常感谢。
System.Runtime.Remoting.RemotingException was unhandled by user code
Message=Remoting cannot find field 'parent' on type 'System.Windows.Forms.Control'.
Source=mscorlib
StackTrace:
at System.Object.GetFieldInfo(String typeName, String fieldName)
at System.Object.FieldGetter(String typeName, String fieldName, Object& val)
at System.Object.FieldGetter(String typeName, String fieldName, Object& val)
at System.Windows.Forms.Control.ControlCollection.Add(Control value)
at AppDomainTest.Shell.Form1.Display(Control control) in c:\temp\AppDomainTest\AppDomainTest\AppDomainTest.Shell\Form1.cs:line 24
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
InnerException:
最佳答案
一位同事向我指出了一个可能的方向:.NET Add-in Framework
为了我的目的,该页面的关键点如下:
The assemblies for these segments are not required to be in the same application domain. You can load an add-in into its own new application domain, into an existing application domain, or even into the host's application domain. You can load multiple add-ins into the same application domain, which enables the add-ins to share resources and security contexts.
关于c# - 从不同的应用程序域(复合 UI)获取对 UserControl 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568955/