将事件处理程序附加到Com事件:InvalidOperationException(S7-PLCSIM)

时间:2016-01-22 20:38:01

标签: c# events com plc

我正在尝试将事件处理程序附加到COM Object的事件。但是我得到了一个InvalidOperationException。

using S7PROSIMLib;

private S7ProSim ps = new S7ProSim();

ps.Connect();
ps.SetScanMode(ScanModeConstants.SingleScan);
ps.BeginScanNotify();

try {
    ps.ScanFinished += Ps_ScanFinished;
    //IS7ProSimEvents_ScanFinishedEventHandler scanFinishedDelegate = new IS7ProSimEvents_ScanFinishedEventHandler(Ps_ScanFinished);
    //ps.ScanFinished += scanFinishedDelegate;
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Source);
    Console.WriteLine(ex.InnerException);
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.StackTrace);
}

private void Ps_ScanFinished(object ScanInfo)
{
    Console.WriteLine("Event fired");
} 

输出是:

event invocation for COM objects requires event to be attributed with DispIdAttribute
   at System.Runtime.InteropServices.ComAwareEventInfo.GetDataForComInvocation(EventInfo eventInfo, Guid& sourceIid, Int32& dispid)
   at System.Runtime.InteropServices.ComAwareEventInfo.AddEventHandler(Object target, Delegate handler)
   at PiPLCSimBridge.Form1.Form1_Load(Object sender, EventArgs e) in C:\PiPLCSimBridge\Form1.cs:Line 72.

我也尝试使用已注释掉的代码,但得到了相同的异常。

附加这样的事件应该有效,这是一个使用相同COM接口is doing it this way.

的流行工具

我的代码有什么问题?

1 个答案:

答案 0 :(得分:4)

幸运的是,我最近遇到了与这个完全相同的COM库完全相同的错误。

问题是由prosim参考中的Embed Interop Types设置引起的。

我通过讨论发现了这个事实 here.

因此,在项目引用部分中,检查prosim引用的属性。确保未设置Embed Interop Types

相关问题