开发者

How do I assign an event handler to an event in C++/CLI?

How do I add "events" to开发者_如何学Python an "event"/delegate? What is the syntax? Is it the same in C++/CLI and in C#?


1: If underlyng delgate of the event is a custom one you define yourself that is a class memeber (example from MSDN):

delegate void Del(int, float);
ref class EventReceiver {
public:
    void Handler(int i , float f) {  }
};
myEventSource->MyEvent += gcnew Del(myEventReceiver, &EventReceiver::Handler);

2: If the underlying delegate is a global handler and has the standard signature for .NET events (object + event args) (from DPD answer):

delegate void MyOwnEventHandler(Object^ sender, EventArgs^ e) { }  
myEventSource->MyEvent += gcnew EventHandler(MyOwnEventHandler);  

3: If the underlying delegate has the standard signature for .NET events and the event handler is a class method:

ref class EventReceiver {
public:
   void Handler(Object^ sender, EventArgs^ e) {  }
};
myEventSource->MyEvent += gcnew EventHandler(myEventReceiver, &EventReceiver::Handler);

4: Using System::EventHandler generic (that takes a MyEventArgs args parameter) as the underlying delegate:

ref class EventReceiver {
public:
   void Handler(Object^ sender, MyEventArgs^ e) {  }
};
myEventSource->MyEvent += gcnew EventHandler<MyEventArgs^>(this, &EventReceiver::DataReceived);


In c#, you do it with the += operator:

someObj.SomeEvent += new EventHandler(Blah_SomeEvent);

...

private void Blah_SomeEvent(object sender, EventArgs e)
{
}

More-than-a-year-later-edit

It has been a long time since I posted this answer and someone noticed me that maybe it was wrong. I really don't know why the OP marked my answer as the right one (maybe OP was looking for this rather than c++-cli syntax? Who knows now).

Anyway, in c++-cli it would be:

someObj->SomeEvent+= gcnew EventHandler(this, &Blah_SomeEvent);


The syntax for C++/CLI is :

delegate void MyOwnEventHandler(Object^ sender, Eventargs^ e)
{

}

to register this for an event:

objectPtr->MyEvent += gcnew EventHandler(MyOwnEventHandler);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜