我有一个 C# 类库,我需要使用 Javascript 调用它。下面是C#类的代码。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms; //required for message box.
namespace csharp.activex.sample
{
[Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938"),
InterfaceType(ComInterfaceType.InterfaceIsDual),
ComVisible(true)]
public interface IHello
{
[DispId(1)]
int ShowDialog();
};
[
Guid("873355E1-2D0D-476f-9BEF-C7E645024C32"),
ProgId("csharpAx.CHello"),
ClassInterface(ClassInterfaceType.None),
ComDefaultInterface(typeof(IHello)),
ComVisible(true)
]
public class CHello : IHello
{
#region [IHello implementation]
public string Hello()
{
return "Hello from CHello object";
}
public int ShowDialog()
{
System.Windows.Forms.MessageBox.Show("C# is awesome");
return 0;
}
#endregion
};
public class Class1
{
public void showDialog() {
MessageBox.Show("Visual c# is awesome!");
}
}
}
我构建了该类,并获得了一个 dll 文件,并将其复制到 c:\DLL。下面的代码用于注册DLL
regasm C:\DLL\ActiveXClass.dll /codebase /tlb
我成功注册了消息类型。
我使用以下 JavaScript 代码创建了一个 html 文件。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type='text/javascript'>
var myAx1;
function startService(){
myAx1 = new ActiveXObject("csharpAx.CHello");
if(myAx1 != null)
{
myAx1.showDialog();
}
else{
alert("failed");
}
return false;
}
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
<a href='#' onclick='return startService()'>StartService</a><br />
</body>
</html>
在由此获得的结果页面上,我单击“启动服务”。但我没有收到任何诸如“失败”或“Visual C# 很棒”之类的警报。
请帮忙
我解决了。需要启用 activex 的安全选项才能执行此操作。
欲了解更多详情,请参阅此论坛帖子。
我认为最好的解决方案是实现 IObjectSafety,如果你信任你的 activex,你不需要让你的用户检查互联网选项。 第 5 点的链接解释了如何操作:http://www.olavaukan.com/2010/08/creating-an-activex-control-in-net-using-c/