如何在Javascript中连接c# ActiveX事件处理程序
本文关键字:ActiveX 事件处理 程序 连接 Javascript | 更新日期: 2023-09-27 17:49:33
利用几个代码片段,我试图将ActiveX对象与Javascript事件处理程序连接起来。我无法确定为什么没有调用事件处理程序。
Github Repository with project.通过在'onLoad'事件中放置对SayHello()的javascript调用,我能够让ActiveX事件触发。现在我正在寻找c#调用,以及如何将其挂钩到Javascript使用的ActiveX对象。
(这也可能依赖于从IE的高级选项中启用本地脚本)。
消息继续
事件处理程序的完成形式与本问题中描述的相同。
<script for="MyObject" event="OnUpdateString(stuff)">
document.write("<p>" + stuff);
document.writeln("</p>");
</script>
利用MSDN文档,我创建了一个WinForms应用程序,其中包含一个WebBrowser控件,作为ObjectForScripting(与问题无关)。这个容器调用ActiveX事件,但是Javascript不处理它。我将c# Form代码包含在ActiveX交互中,并允许它成为ActiveX和/或WebBrowser控件的未来用户的参考。
此文件用于在主窗口中添加WebBrowser控件的新Windows窗体项目。
c# Form1.csusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ActiveXObjectSpace;
namespace TestActiveX
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
MyObject myObject = new MyObject();
public Form1()
{
InitializeComponent();
Text = "ActiveX Test";
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.ObjectForScripting = this;
webBrowser1.Url = new Uri(@"C:'path'to'TestPage.html");
// Call ActiveX
myObject.SayHello("C# Launch");
}
public string ControlObject()
{
return "<p>Control Object Called.</p>";
}
}
}
结合其他两个代码片段的帮助,我创建了一个ActiveX对象。如前所述,需要在构建后进行注册。
c# ObjectX.cs using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
/// http://blogs.msdn.com/b/asiatech/archive/2011/12/05/how-to-develop-and-deploy-activex-control-in-c.aspx
/// https://stackoverflow.com/questions/11175145/create-com-activexobject-in-c-use-from-jscript-with-simple-event
///
/// Register with %NET64%'regasm /codebase <full path of dll file>
/// Unregister with %NET64%'regasm /u <full path of dll file>
namespace ActiveXObjectSpace
{
/// <summary>
/// Provides the ActiveX event listeners for Javascript.
/// </summary>
[Guid("4E250775-61A1-40B1-A57B-C7BBAA25F194"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IActiveXEvents
{
[DispId(1)]
void OnUpdateString(string data);
}
/// <summary>
/// Provides properties accessible from Javascript.
/// </summary>
[Guid("AAD0731A-E84A-48D7-B5F8-56FF1B7A61D3"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IActiveX
{
[DispId(10)]
string CustomProperty { get; set; }
}
[ProgId("MyObject")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
[Guid("7A5D58C7-1C27-4DFF-8C8F-F5876FF94C64")]
[ComSourceInterfaces(typeof(IActiveXEvents))]
public class MyObject : IActiveX
{
public delegate void OnContextChangeHandler(string data);
new public event OnContextChangeHandler OnUpdateString;
// Dummy Method to use when firing the event
private void MyActiveX_nMouseClick(string index)
{
}
public MyObject()
{
// Bind event
this.OnUpdateString = new OnContextChangeHandler(this.MyActiveX_nMouseClick);
}
[ComVisible(true)]
public string CustomProperty { get; set; }
[ComVisible(true)]
public void SayHello(string who)
{
OnUpdateString("Calling Callback: " + who);
}
}
}
最后是要被浏览器或容器加载的html页面。它成功加载ActiveX对象并包含OnUpdateString的事件处理程序。它检查ActiveX提供的函数SayHello是否可以被调用,并进行调用。
我希望Javascript和c#调用被写入文档,但是没有这样的条目被写入。
TestPage.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DemoCSharpActiveX webpage</title>
</head>
<body>
<script type="text/javascript">
window.objectLoadFailure = false;
</script>
<object id="MyObject" onerror="window.objectLoadFailure = true" classid="clsid:7A5D58C7-1C27-4DFF-8C8F-F5876FF94C64"></object>
<script for="MyObject" event="OnUpdateString(stuff)">
document.write("<p>" + stuff);
document.writeln("</p>");
</script>
<script type="text/javascript">
document.write("<p>Loaded ActiveX Object: " + !window.objectLoadFailure);
document.writeln("</p>");
if (typeof window.external.ControlObject !== "undefined") {
document.write(window.external.ControlObject());
}
var obj = document.MyObject;
if (typeof obj.SayHello !== "undefined") {
document.writeln("<p>Can Call say hello</p>")
}
obj.SayHello("Javascript Load");
</script>
</body>
</html>
包含的页面显示了这个输出
已加载ActiveX对象:true
Control Object Called.
Can Call say hello
更新的,只要你可以从HTML (MyObject.object != null
)中获得<object>
实例化,JavaScript事件处理程序的最终问题很简单,你在调用MyObject.SayHello("Javascript Load")
之前用document.write
杀死原始HTML文档,并用<p>Loaded ActiveX Object: ...</p>
替换它。到那时,所有原始的JavaScript事件处理程序都将消失。
因此,以下工作正常,事件被触发并处理(使用alert
):
<!DOCTYPE html>
<html>
<head>
<title>DemoCSharpActiveX webpage</title>
</head>
<body>
<script type="text/javascript">
window.objectLoadFailure = false;
</script>
<object id="MyObject" onerror="window.objectLoadFailure = true" classid="clsid:7A5D58C7-1C27-4DFF-8C8F-F5876FF94C64"></object>
<script type="text/javascript" for="MyObject" event="OnUpdateString">
alert("Hello from event handler");
</script>
<script type="text/javascript" for="window" event="onload">
alert("Hello from window.onload!");
alert(MyObject.object);
MyObject.SayHello("Javascript Load");
</script>
</body>
</html>
要使原始逻辑工作,您可以直接操作DOM而不是使用document.write
。或者,至少在OnUpdateString
被触发并处理后调用它。
现在我已经看到了完整的源代码,我可以看出这里有不少地方出了问题。
您可以在
SayHello
中击中断点,因为您从c# [MyObject myObject = new MyObject()
]创建MyObject
并从c# [myObject.SayHello("C# Launch")
]调用它。删除它,你会看到它永远不会被调用,当你从JavaScript调用[obj.SayHello("Javascript Load")
]。这导致了另一个问题:
<object>
没有成功创建,更重要的是,你的JavaScript脚本甚至都没有运行,因为你的测试HTML文件是从本地文件系统(通过file://
协议)提供的。这是一个安全限制。试着像下面这样修改你的脚本,看看有没有警报显示:<script type="text/javascript" for="window" event="onload"> alert("Hello from window.onload!"); alert(MyObject.object) // null! object wasn't created... document.write("<p>Loaded ActiveX Object: " + !window.objectLoadFailure); document.writeln("</p>"); if (typeof window.external.ControlObject !== "undefined") { document.write(window.external.ControlObject()); } var obj = document.MyObject; if (typeof obj.SayHello !== "undefined") { document.writeln("<p>Can Call say hello</p>") } obj.SayHello("Javascript Load"); </script>
有几种方法可以修复它。最简单的一种可能是使用"Web标记"。最困难的是提供
IInternetSecurityManager
的自定义实现。我自己会使用另一种方法-互联网功能控制-并禁用FEATURE_LOCALMACHINE_LOCKDOWN
,FEATURE_BLOCK_LMZ_SCRIPT
,FEATURE_BLOCK_LMZ_OBJECT
密钥。您可以使用以下代码,我改编自我的其他相关答案:// static constructor, runs first static Form1() { SetWebBrowserFeatures(); } static void SetWebBrowserFeatures() { // don't change the registry if running in-proc inside Visual Studio if (LicenseManager.UsageMode != LicenseUsageMode.Runtime) return; var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); var featureControlRegKey = @"HKEY_CURRENT_USER'Software'Microsoft'Internet Explorer'Main'FeatureControl'"; Registry.SetValue(featureControlRegKey + "FEATURE_BROWSER_EMULATION", appName, GetBrowserEmulationMode(), RegistryValueKind.DWord); // enable the features which are "On" for the full Internet Explorer browser Registry.SetValue(featureControlRegKey + "FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", appName, 1, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_AJAX_CONNECTIONEVENTS", appName, 1, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_GPU_RENDERING", appName, 1, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_WEBOC_DOCUMENT_ZOOM", appName, 1, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_NINPUT_LEGACYMODE", appName, 0, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_LOCALMACHINE_LOCKDOWN", appName, 0, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_BLOCK_LMZ_SCRIPT", appName, 0, RegistryValueKind.DWord); Registry.SetValue(featureControlRegKey + "FEATURE_BLOCK_LMZ_OBJECT", appName, 0, RegistryValueKind.DWord); } static UInt32 GetBrowserEmulationMode() { int browserVersion = 0; using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE'Microsoft'Internet Explorer", RegistryKeyPermissionCheck.ReadSubTree, System.Security.AccessControl.RegistryRights.QueryValues)) { var version = ieKey.GetValue("svcVersion"); if (null == version) { version = ieKey.GetValue("Version"); if (null == version) throw new ApplicationException("Microsoft Internet Explorer is required!"); } int.TryParse(version.ToString().Split('.')[0], out browserVersion); } if (browserVersion < 7) { throw new ApplicationException("Unsupported version of Microsoft Internet Explorer!"); } UInt32 mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. switch (browserVersion) { case 7: mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. break; case 8: mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. break; case 9: mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. break; case 10: mode = 10000; // Internet Explorer 10. break; } return mode; }
现在,您的脚本确实运行了,但是仍然没有创建
<object>
(alert(MyObject.object)
显示null
)。最后,您需要在ActiveX对象上实现IObjectSafety
接口,并将其站点锁定到您自己的HTML页面。如果没有适当的IObjectSafety
,对象将不会在默认的IE安全设置下创建。如果没有站点锁定,它可能会成为一个巨大的安全威胁,因为任何恶意脚本都可能在应用程序的上下文中创建和使用您的对象。
更新以解决注释:
我已经用您提供的示例更新了项目,请注意我已经做了一个改变,这样就有了一个c#按钮和一个Javascript按钮触发事件。JS按钮工作,但c#不触发。我寻找"Hello from: c# button"警报。
在你的代码中,myObject
实例被创建并访问,只在c#中:
MyObject myObject = new MyObject();
// ...
private void button1_Click(object sender, EventArgs e)
{
// Call ActiveX
myObject.SayHello("C# Button");
}
此实例与您从HTML创建的<object id="MyObject" onerror="window.objectLoadFailure = true" classid="clsid:7A5D58C7-1C27-4DFF-8C8F-F5876FF94C64"></object>
实例无关。它们是两个独立的,不相关的对象。事件处理程序只适用于后一个<object>
实例。你甚至不订阅new MyObject()
实例上的任何事件。
如果我没理解错的话,你需要这个:
private void button1_Click(object sender, EventArgs e)
{
// Call ActiveX
//myObject.SayHello("C# Button");
this.webBrowser1.Document.InvokeScript("eval",
new[] { "MyObject.SayHello('C# Button')" });
}
现在,JavaScript事件处理程序将被调用,您将看到"C# Button"
警报。