一、COM可见及GUID
项目属性 –> 应用程序 –> 程序集信息:
为程序生成一个GUID填写在此处,并勾选“使程序集 COM 可见”
二、修改AssemblyInfo.cs文件:
//添加一行命名空间 using System.Security; //添加一行标记 [assembly: AllowPartiallyTrustedCallers()]
三、类的实现
1. 标记GUID
[Guid("88E22812-2AFF-4c87-AB0B-D3C650BB9BF8")] public partial class OcxTest : UserControl
{ }
2. 声明IObjectSafety接口
[ComImport,Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IObjectSafety { [PreserveSig] void GetInterfacceSafyOptions( int riid, out int pdwSupportedOptions, out int pdwEnabledOptions); [PreserveSig] void SetInterfaceSafetyOptions( int riid, int dwOptionsSetMask, int dwEnabledOptions); }
3.实现IObjectSafety接口
[Guid("88E22812-2AFF-4c87-AB0B-D3C650BB9BF8")] public partial class OcxTest : UserControl, IObjectSafety { //Other lines #region IObjectSafety 成员 void IObjectSafety.GetInterfacceSafyOptions(int riid, out int pdwSupportedOptions, out int pdwEnabledOptions) { pdwSupportedOptions = 1; pdwEnabledOptions = 2; } void IObjectSafety.SetInterfaceSafetyOptions(int riid, int dwOptionsSetMask, int dwEnabledOptions) { throw new NotImplementedException(); } #endregion }
4.【可选】为注册和注销实现更多操作,注册和注销时会执行如下方法
[Guid("88E22812-2AFF-4c87-AB0B-D3C650BB9BF8")] public partial class OcxTest : UserControl, IObjectSafety { //Other lines ///<summary> ///Register the class as a control and set its CodeBase entry ///</summary> ///<param name="key">The registry key of the control</param> [ComRegisterFunction()] public static void RegisterClass(string key) { // } ///<summary> ///Called to unregister the control ///</summary> ///<param name="key">Tke registry key</param> [ComUnregisterFunction()] public static void UnregisterClass(string key) { // } }
四、注册和注销
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm.exe" /codebase OcxTest.dll
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm.exe" /codebase OcxTest.dll /u
五、调用
<object id="p" border="0" classid="CLSID:88E22812-2AFF-4c87-AB0B-D3C650BB9BF8" width="300" height="280"> </object>
结束。
(时间及其仓促,写的很简略,立此存档以备后用)