zoukankan      html  css  js  c++  java
  • vs2010创建com组件

    vs2010创建com组件
    ?//打开vs2010 新建一个类库项目ComTest
    //新建一个加法的接口IComTest,代码如下:
    //在用C#创建COM组件时,一定要记住以下几点:
    //1:所要导出的类必须为公有;
    //2:所有属性、方法也必须为公有;
    //3:要导出的属性、方法必须用接口方式;如果没有在接口中声明,即使该方法(属性)为公有,也不能正常导出到COM。但他们可以被别的.NET程序所使用;
    //可以用VS2010的命令提示符中输入:guidgen 就会出来它的窗口。在几个复选框选择最后一个Registry Format,点击New Guid,然后COPY就行

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //因为Guid是属性,应该用的是System.Runtime.InteropServices.GuidAttribute而不是System.Guid
    using System.Runtime.InteropServices;
    namespace ComTest
    {

    [Guid("C3FE262B-5831-484c-BDF1-05AAFFF8F862")]
    public interface IComTest
    {
    [DispId(1)]//[DispId(1)]为函数的标识。如果有多个函数可相应的在函数前面加[DispId(2)].....
    int Add(int a, int b);
    [DispId(2)]
    string HelloWord(string name);
    }
    //InterfaceType表求向COM公开的方式,这里选择为以调度的方式向COM公开
    [Guid("D11FEA37-AC57-4d39-9522-E49C4F9826BB"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    //创建事件接口
    public interface IComTest_Events
    {

    }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //因为Guid是属性,应该用的是System.Runtime.InteropServices.GuidAttribute而不是System.Guid
    using System.Runtime.InteropServices;
    namespace ComTest
    {
    [Guid("2E3C7BAD-1051-4622-9C4C-215182C6BF58"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IComTest_Events))]
    public class ComTest : IComTest//接口实现类
    {
    public int Add(int a, int b)
    {
    return a + b;
    }
    public string HelloWord(string name)
    {
    return "你好"+name;
    }
    }
    }

    至此,代码就OK了。
    由于COM需要注册,注册时要加密钥文件.SNK,下面我们说下如何生成.snk文件
    进入VS2010命令提示符。用命令:sn -k ComTest.snk回车(注意:以管理员身份运行)
    这是命令提示符的路径:C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC
    相应生成的文件就在vc文件夹下面。将其考到项目根目录下。
    打开AssemblyInfo.cs。在里面加入[assembly:AssemblyKeyFile("ComTest.snk")]
    [assembly: ComVisible(false)] 修改为true。

    项目属性->生成->选中“为COM互操作注册
    生成(*^__^*) OK

    下面看下客户端利用js调用com组件
    代码如下:
    ?<html>
    <body>
    <object classid="clsid:2E3C7BAD-1051-4622-9C4C-215182C6BF58" id="MyComTest" width="286" height="225">
    </object>
    <script language="JavaScript">
    <!--
    var wmp;
    wmp = document.getElementById("MyComTest");
    //var iResult=wmp.Add(4,9);
    //alert(iResult);
    var iResult=wmp.HelloWord("wanghk");
    alert(iResult);
    </script>
    </body>
    </html>

  • 相关阅读:
    【LeetCode】17. Letter Combinations of a Phone Number
    【LeetCode】16. 3Sum Closest
    【LeetCode】15. 3Sum 三个数和为0
    【LeetCode】14. Longest Common Prefix 最长前缀子串
    【LeetCode】13. Roman to Integer 罗马数字转整数
    【LeetCode】12. Integer to Roman 整型数转罗马数
    【LeetCode】11. Container With Most Water
    【LeetCode】10. Regular Expression Matching
    Models of good programmer
    RSA Algorithm
  • 原文地址:https://www.cnblogs.com/xianyin05/p/3051722.html
Copyright © 2011-2022 走看看