Here’s step by step instructions of how to create a callback function which allows a function in one class to be called by some other class it is using (for instance, you may have a class you’ve created that provides communication functions and you want to pass received data back to the main class or your form whenever it gets received).


//TO ADAPT FOR EACH USE, FIND AND REPLACE THE FOLLOWING:
//	NAME						CHANGE TO
//	ThisClassName				Name of the class that contains the function to be called.
//	ProcessNewEventFunction		Name of the function that will be called by the callback (in the class that contains the function to be called).
//	ProcessNewEventFunction_Def	Same as the name used ProcessNewEventFunction but made different, e.g. by adding _def to the end.
//	OtherClassName				Name of the class that will be calling back (the other class)
//	OtherClassObject1			Name of the other class object in the class which will be called back
//	SetMyCallbackFunction			Function to call in the other class to set the callback function it should call back
//	OtherClassCallbackFunction1		Object in the other class which stores the function to be called back.

In Class That Contains Function To Be Called

Create the function to be called:

	public: void ThisClassName::ProcessNewEventFunction (String ^SomeTextIWantToPassForExample)
	{
	}
Call other class function that we are passing the callback delegate to:

	//Set our callback function
	ProcessNewEventFunction_Def ^del = gcnew ProcessNewEventFunction_Def(this, &ThisClassName::ProcessNewEventFunction); 	//Class::FunctionName
	OtherClassObject1->SetMyCallbackFunction(del);

In Class That Needs To Call The Function

Define delegate handler somewhere outside of the class (i.e. inside .h file namespace but before public ref class)

	public delegate void ProcessNewEventFunction_Def (String ^SomeTextIWantToPassForExample);
Define object to store passed delegate

	private: ProcessNewEventFunction_Def ^OtherClassCallbackFunction1;
Create function to receive the delegate and store it

	public: void OtherClassName::SetMyCallbackFunction(ProcessNewEventFunction_Def ^del)
	{
		OtherClassCallbackFunction1 = del;
	}
To call the function

	if (OtherClassCallbackFunction1 != nullptr)
		OtherClassCallbackFunction1("12345");
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.