what is the C++/CLI syntax to subscribe for events?

前端 未结 2 354
野的像风
野的像风 2020-12-11 18:25

I\'m updating some old Managed C++ code with lines like this:

instanceOfEventSource->add_OnMyEvent( 
    new EventSource::MyEventHandlerDelegate(this, MyE         


        
相关标签:
2条回答
  • 2020-12-11 18:34

    I just spent half an hour trying to figure out how to register a static method as callback method for an event. While the OP did not specifically ask for registering static methods, this will be helpful to others facing the same problem. It's actually very simple, in that case the delegate constructor takes just one parameter for the static target method.

    Example:

    System::EventHandler^ h = gcnew System::EventHandler(&MyClass::MyStaticCallbackMethod);
    
    0 讨论(0)
  • 2020-12-11 18:48

    The syntax is similar to C#'s, in other words, += is overloaded to make this possible:

    instanceOfEventSource.MyEvent +=
        gcnew EventSource::MyEventHandlerDelegate(this, &MyClass::MyEventHandlerMethod);
    

    Analogously for removal. Unlike C#, however, you may not omit the explicit instantiation of the event handler delegate so this produces quite long-winded code.

    0 讨论(0)
提交回复
热议问题