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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值