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

Attaching an event handler to a Com event: InvalidOperationException (S7-PLCSIM)

我正在尝试将事件处理程序附加到 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.

我的代码有什么问题?

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

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

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

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