Search code examples
c#javascriptvb.netactivex

Triggering C# dll using Javascript ActiveX Object


I have a c# class library which I need to call using Javascript. Below is the code of C# class.

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!");
            }
    }
}

I build the class and I get a dll file which I copied to c:\DLL. Below code is used to register the DLL

regasm C:\DLL\ActiveXClass.dll /codebase /tlb

I get the message types registered successfully.

I create a html file with following javascript code.

<!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>

On the result page thus obtained I click on start service. But I do not get any alerts like "failed" or "Visual C# is awesome".

Please help


Solution

  • I solved it. There is a Security option for activex that needs to be enabled for doing this.

    For more details see this forum post.