ActiveX 控件中调用 JavaScript 方法
1. 添加接口 【IOleContainer】,代码如下
[ComImport, Guid("0000011B-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleContainer
{
void EnumObjects([In, MarshalAs(UnmanagedType.U4)] int grfFlags, [Out, MarshalAs(UnmanagedType.LPArray)] object[] ppenum);
void ParseDisplayName([In, MarshalAs(UnmanagedType.Interface)] object pbc, [MarshalAs(UnmanagedType.BStr)] string pszDisplayName, [Out, MarshalAs(UnmanagedType.LPArray)] int[] pchEaten, [Out, MarshalAs(UnmanagedType.LPArray)] object[] ppmkOut);
void LockContainer([In, MarshalAs(UnmanagedType.I4)] int fLock);
}
2. 添加接口 【IOleClientSite】,代码如下
[Guid("00000118-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleClientSite
{
void SaveObject();
void GetMoniker(uint dwAssign, uint dwWhichMoniker, object ppmk);
void GetContainer(out IOleContainer ppContainer);
void ShowObject();
void OnShowWindow(bool fShow);
void RequestNewObjectLayout();
}
3. 调用JS方法的代码如下
参数 functionName 为 JS 方法名称
参数 paras 是 String 类型,可以使用特定规则组合多个值
private void CallJavaScriptMethod(string functionName, string paras)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public;
Type typeIOleObject = this.GetType().GetInterface("IOleObject", true);
object objClientSite = typeIOleObject.InvokeMember("GetClientSite", bindingFlags, null, this, null);
IOleClientSite oleClientSite = objClientSite as IOleClientSite;
IOleContainer oleContainer;
oleClientSite.GetContainer(out oleContainer);
object[] args = new object[1];
args[0] = paras;
IHTMLDocument htmlDocument = (IHTMLDocument)oleContainer;
object script = htmlDocument.Script;
try
{
script.GetType().InvokeMember(functionName, bindingFlags, null, script, args);
}
catch { }
}