1. 首先新建项目--->类库,取名:ActiveXDemo
  2. 右键项目属性:应用属性==>程序集信息=>使程序集Com可见,
  3. 生成==>输出==>为com互操作注册
  4. 新建接口类取名:IObjectSafety,以下代码可直接用,最好不要修改
复制代码
 1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Runtime.InteropServices;  5 using System.Text;  6  7 namespace ActiveXDemo  8 {  9     [ComImport, Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")] 10     [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 11     public interface IObjectSafety 12     { 13         [PreserveSig] 14         int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions); 15         [PreserveSig()] 16         int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions); 17     } 18 }
复制代码

新建用户控件取名:UserControl1,UserControl1继承自上面新建的接口IObjectSafety,并实现接口(实现接口的方法请复制下面的内容),在类UserControl1添加Guid特性值,利用VS的工具生成guid

 

复制代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices;  namespace ActiveXDemo {     [Guid("C5BD015D-E2AA-4DD3-AEB7-93D7409FA751")]     public partial class UserControl1 : UserControl, IObjectSafety     {         public UserControl1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             MessageBox.Show("ActiveXDemo");         }