C#编写COM组件

C#编写COM组件

 

 

一.先创建类库项目

二.Project-》Property-》Application-》Assembly Information-》Make Assembly Com Visiable

三.Property-》Build->Register for Com Interop

四.Property-》Signing-》Create a new key

五.编码

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Runtime.InteropServices;

 

namespaceCOMCOM

{

    [ComVisible(true)]

    [Guid("2CBD3D76-35F1-4f9d-9C1B-9DBFEE412F76")]

    publicinterfaceIMarcus

    {

        void Initialize();

        void Dispose();

        int Add(int x, int y);

    }

 

    [ComVisible(true)]

    [Guid("EA2F140A-108F-47ae-BBD5-83EEE646CC0D")]

    publicclassComForMarcus:IMarcus

    {

        #regionIMarcus Members

 

        publicvoid Initialize()

        {

            //throw new NotImplementedException();

        }

 

        publicvoid Dispose()

        {

            //throw new NotImplementedException();

        }

 

        publicint Add(int x, int y)

        {

            return x + y;

        }

 

        #endregion

    }

}

六.Visual Studio Command Prompt-》regasm COMCOM.dll 注册成功,可以在OLE/COM Object Viewer中查看

Javascript call Com:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function callCom() {
            var comObj = new ActiveXObject("COMCOM.ComForMarcus");
            var result = comObj.Add(22, 33);
            alert(result);
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="button" onclick="callCom();" />
    </div>
    </form>
</body>
</html>

需要在IE安全设置中启用不安全的ActiveX控件,才能正确显示。

 

posted @ 2012-02-07 14:48  zzljh  阅读(369)  评论(0编辑  收藏  举报