How to cast a control to IOleObject

被刻印的时光 ゝ 提交于 2019-12-06 14:15:51

The IOleObject interface is a nested interface inside the internal UnsafeNativeMethods class in the System.Windows.Forms assembly. The System.Windows.Forms.Control implements it internally, and explicitly.

Creating another interface with the same name and guid will not make it "the same interface" on a managed level.

This line

IOleObject obj = (IOleObject) this;

represents managed .net casting, and has nothing to do with COM. This cast will work only with the exact same interface from the winforms assembly, which isn't public.

You could try to use reflection via the InterfaceMapping structure to get the method (but note that this is not recommendable):

Type thisType = this.GetType();

Type oleInterface = thisType.GetInterface("IOleObject");

MethodInfo getSiteMethod = oleInterface.GetMethod("GetClientSite");

//InterfaceMapping is used to get more complex interface scenarios
InterfaceMapping map = thisType.GetInterfaceMap(oleInterface);

//at which index is the explicit implementation
int index = Array.IndexOf(map.InterfaceMethods, getSiteMethod);
MethodInfo actualExplicitMethod = map.TargetMethods[index];

//late-bound call (slow)
object o = actualExplicitMethod.Invoke(this, new object[] { });

Now, first, you get an internal type wrapped in System.Object which cannot be cast to your interface since the original interface is internal, so you get to have more fun with reflection as long as you intend to use that object.

Second, I've tried it, the technique works, but in your specific scenario this method called on a windows Form throws an exception - "Top-level Windows Forms control cannot be exposed as an ActiveX control.".

I'm using this method:

IOleClientSite pClientSite = (IOleClientSite)Site.GetService(new AntiMoniker().GetType());

Define AntiMoniker for example. For now, detail is not required. Just get a instance of System.__ComObject.

[ComImport(), Guid("00000305-0000-0000-C000-000000000046")]
class AntiMoniker {
}

It'll work on .NET Framework 2.0/IE8/WinXP SP3

Thanks

noseratio

Here is another method, using Marshal.CreateAggregatedObject to get to the private COM interfaces.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!