问题描述
|
我的.NET程序中有Webbrowser控件。实际上,使用哪个.net包装器(wpf或winforms)都没有关系,因为它们都包装了ActiveX组件“ Microsoft Internet控件”(ieframe.dll)。
因此,我将一些html / js代码加载到Webbrowser中。此代码尝试创建一些ActiveX并失败。将相同的代码加载到完整的IE中后,可以正常工作。但是在Webbrowser中失败:新的ActiveXObject(\“ myprogid \”)抛出\“自动化服务器无法创建对象\”。
Webbrowser控件是否具有允许创建ActiveX的功能?
更新:我添加了\“
<!-- saved from url=(0014)about:internet -->
\“
在加载到Webbrowser的html的顶部。它没有帮助。
解决方法
这是WPF的解决方法。
MainWindow.xaml:
<Window x:Class=\"MainWindow\"
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"
xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"
xmlns:wf=\"clr-namespace:System.Windows.Forms;assembly=system.windows.forms\"
>
<Grid>
<WebBrowser x:Name=\"webBrowser\" SnapsToDevicePixels=\"True\" >
</WebBrowser>
</Grid>
</Window>
MainWindow.xaml.cs:
public void Run(Uri uri)
{
m_gateway = new HostGateway
{
MyComponent = SomeNativeLib.SomeNativeComponent
};
webBrowser.ObjectForScripting = m_gateway;
webBrowser.Navigate(\"about:blank\");
webBrowser.Navigate(uri);
}
[ComVisible(true)]
public class HostGateway
{
public SomeNativeLib.SomeNativeComponent MyComponent {get;set;}
}
而且,我们需要添加本地库作为参考:
<Reference Include=\"SomeNativeLib,Version=1.0.0.0,Culture=neutral,processorArchitecture=MSIL\">
<EmbedInteropTypes>True</EmbedInteropTypes>
<HintPath>..\\..\\..\\References\\SomeNativeLib.dll</HintPath>
</Reference>
然后,在我们的客户端js代码中,我们必须通过window.external访问HostGateway实例:
window.external.MyComponent.foo();
,我最近遇到了同样的问题,我的解决方法(不需要任何其他引用)只是拥有一个名为ActiveXObject的javascript函数和一个调用Activator.CreateInstance的C#函数,这非常简单:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
[ComVisible(true)]
public class TestForm :
Form {
public Object newActiveXObject(String progId) {
return(Activator.CreateInstance(Type.GetTypeFromProgID(progId)));
}
public TestForm() {
Controls.Add(
new WebBrowser() {
ObjectForScripting = this,DocumentText =
\"<script>\" +
\"function ActiveXObject(progId) { return(window.external.newActiveXObject(progId)); }\" +
\"document.write(\'<pre>\' + new ActiveXObject(\'WScript.Shell\').exec(\'cmd /c help\').stdOut.readAll() + \'</pre>\');\" +
\"</script>\",Dock = DockStyle.Fill
}
);
}
[STAThread]
public static void Main() {
Application.EnableVisualStyles();
Application.Run(new TestForm());
}
}