现在的位置: 首页 > 综合 > 正文

c#编写com组件以及在silverlight中调用

2012年08月30日 ⁄ 综合 ⁄ 共 1256字 ⁄ 字号 评论关闭

c#编写com组件

  1.新建windows类库应用程序,在properties目录AssemblyInfo文件中,将ComVisible(False)设置成ComVisible(true)。

  2.在项目属性,build选项,勾选register for com interop。

  3.编写com代码(sensorEvents定义事件接口)。

  如下:

  

代码

namespace IMDCOM
{
/// <summary>
/// 事件接口
/// </summary>
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
/// <summary>
/// 定义要暴露的事件
/// </summary>
void OnHelloBegin(object sender, EventArgs e);
}

public class HelloEvents : EventArgs
{}

/// <summary>
/// 自定义定义委托
/// </summary>
public delegate void Comdel(object sender, EventArgs e);

[ComVisible(
true)]
[ComSourceInterfaces(
typeof(IComEvents))]
public class IMDCOMTEST
{
public string Hello()
{
if (OnHelloBegin!=null)
OnHelloBegin(
this,new HelloEvents());
return "asdasdasd";
}

/// <summary>
/// 实现事件接口
/// </summary>
public event Comdel OnHelloBegin;
}
}

  

  4.编译dll,使用命令C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe SensorsCom.dll注册com。

到此c#写COM已经OK了!

silverlight中调用com

  1.将silverlight程序设置为最高权限,OOB模式。否则silverlight不能调用com。

  2.调用代码

  如下:

  

代码

using (dynamic IMDCOM = AutomationFactory.CreateObject("IMDCOM.IMDCOMTEST"))
{
AutomationEvent eve
= AutomationFactory.GetEvent(IMDCOM, "OnHelloBegin");
eve.EventRaised
+=new EventHandler<AutomationEventArgs>((s,e1)=>{
MessageBox.Show(e1.Arguments[
0].ToString());
});

dynamic SensorList
= IMDCOM.Hello();
MessageBox.Show(SensorList);
}

抱歉!评论已关闭.