C#编写COM组件

C#编写COM组件 

软件:Microsoft VisualStudio 2010

1、新建一个类库项目


2、将Class1.cs改为我们想要的名字(例如:MyClass.cs)


问是否同时给类改名,确定


3、修改Properties目录下面的AssemblyInfo.cs

ComVisible属性设置为true

改成下图


4、项目->MyLib属性

切换到“生成”选项卡,在底部位置,勾选“COM互操作注册


切换到“签名”选项卡

  勾选“为程序集签名

  在下面的下拉框里面选择“<新建...>


5、在弹出的对话框里面,输入MyKey。。或者随便取个名字

  去掉“使用密码保护文件(P)”的选项


6、开始编码,任何一个公开的类,必须有一个 I开通的接口定义

C# Code

[csharp]  view plain  copy
 print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Runtime.InteropServices;  
  5.   
  6. namespace MyLib  
  7. {  
  8.     [ComVisible(true)]  
  9.     [Guid("35A5CE1E-551C-41EC-81D4-005318550119")]  
  10.     public interface IMyClass  
  11.     {  
  12.         void Initialize();  
  13.         void Dispose();  
  14.         int Add(int x, int y);  
  15.     }  
  16.     [ComVisible(true)]  
  17.     [Guid("F0239BF9-0A6E-49A6-8853-BADE1B95E66F")]  
  18.     [ProgId("MyLib.MyClass")]  
  19.     public class MyClass : IMyClass  
  20.     {  
  21.         public void Initialize()  
  22.         {  
  23.             // nothing to do  
  24.         }  
  25.   
  26.         public void Dispose()  
  27.         {  
  28.             // nothing to do  
  29.         }  
  30.   
  31.         public int Add(int x, int y)  
  32.         {  
  33.             return x + y;  
  34.         }  
  35.     }  
  36. }  

7、GUID属性里面的那个字符串,在“工具”菜单下面,“创建 GUID

  选择  [GUID(“xxxxxxxxxx-xxxx….xxxxxx”)],然后复制


8、编译&注册

编译:生成->生成解决方案(F6)。如果没有生成.tlb文件,需要用管理员身份打开Visual Studio 2010,然后重新编译

注册过程:

开始→所有程序→Microsoft Visual Sutdio 2010→Visual Studio Tools→Visual Studio命令提示符(2010)〖注:以管理员身份运行〗

在命令提示符下面,进入Dll所在的目录

C:\Windows\system32>cd/d E:\MyLib\MyLib\bin\Debug

用 gacutil /i MyLib.dll 将这个DLL加入的全局缓存里

E:\MyLib\MyLib\bin\Debug>gacutil/i mylib.dll

然后用 regasm MyLib.dll 注册这个dll

E:\MyLib\MyLib\bin\Debug>regasmmylib.dll

  • 8
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值