平台:VS2K5
一、AssemblyInfo.cs中设置COM权限
1、设置应用该属性的对象是否对COM可见
增加[assembly: ComVisible(true)]
2、设置安全策略授予完全信任的其他程序集才可以调用此程序集
增加[assembly: AllowPartiallyTrustedCallers()]
二、在Com类代码中进行设置
1、为主类增加Guid
增加[Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")]
2、增加IObjectSafety接口,接口的Guid必须为CB5BDC81-93C1-11CF-8F20-00805F2CD064
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IObjectSafety
{
// methods
void GetInterfacceSafyOptions(
System.Int32 riid,
out System.Int32 pdwSupportedOptions,
out System.Int32 pdwEnabledOptions);
void SetInterfaceSafetyOptions(
System.Int32 riid,
System.Int32 dwOptionsSetMask,
System.Int32 dwEnabledOptions);
}
3、增加对外开放事件,可以使用javascript进行回调
[GuidAttribute("yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface IControlEvents
{
[DispIdAttribute(0x00000001)]
void OnEvt1(string eventmask);
[DispIdAttribute(0x00000002)]
void OnEvt2(int param1, int param2);
}
4、增加对外开放接口
[GuidAttribute("zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz")]
public interface ILoadEvents
{
[DispId(0x00000001)]
int Func1(string param1);
[DispId(0x00000003)]
int Func2(string ext, string ip, string port);
[DispId(0x00000005)]
int Func3();
}
5、添加delegate
delegate返回值、函数参数类型需要和事件声明中相一致。
如:void OnEvt1(string param1);
添加public delegate void HandleEvt1(string param1);
6、在主类中添加属性和接口
添加 [ClassInterface(ClassInterfaceType.AutoDispatch), ComSourceInterfaces(typeof(IControlEvents))]属性,设置事件的分发方式和分发源
添加 [ProgId("@xxxx")]属性
添加IObjectSafety接口,并实现
public void GetInterfacceSafyOptions(Int32 riid, out Int32 pdwSupportedOptions, out Int32 pdwEnabledOptions)
{
// TODO: 添加 WebCamControl.GetInterfacceSafyOptions 实现
pdwSupportedOptions = 1;
pdwEnabledOptions = 2;
}
public void SetInterfaceSafetyOptions(Int32 riid, Int32 dwOptionsSetMask, Int32 dwEnabledOptions)
{
// TODO: 添加 WebCamControl.SetInterfaceSafetyOptions 实现
}
添加ILoadEvents接口,并实现
添加Events,名字和IControlEvents中的名字一样,如:
public event HandleEvt1 OnEvt1;
7、设置项目属性
在“生成”标签中,勾选为“COM Interop注册”
三、注册与查看
可以新建一个安装项目安装COM组件,添加安装项目完毕之后,将Register属性设置成为“vsdrpCOM ”
控件注册完毕之后,可以使用VC6自带工具OLE view进行查看,“Object Classes -> Group by Component Category -> .NET Category”中
四、在浏览器中调用
1、添加Object
<object id="ctrl" classid="clsid:B03BAB38-3881-486F-9CAD-1E6DC51D4E5F" codebase="ICPhoneCOM.msi" width="0" height="0">
2、调用COM中的函数
在JS的 函数中添加代码 document.getElementById('ctrl').Func3();
3、添加事件处理
function ctrl::OnEvt1(str)
{
//代码内容
}