我有一個c#類庫,我需要使用Javascript調用。以下是C#類的代碼。使用Javascript ActiveX對象觸發C#dll
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#很棒」。
請幫忙
確保你使用的是IE瀏覽器。還檢查控制檯的錯誤(假設IE8 +) –
我使用的是IE9! –
@AlvinWong在控制檯中出現錯誤。 SCRIPT429:自動化服務器無法創建對象 –