You are definitely doing too much regarding Question #1. You don't need to create an object every time you need to fire an event. I'm sorry my example code wasn't better. I just typed it into a text editor. I should have grabbed it from a working project. Regarding Question #2, there's definitely a better way. I just stuck everything into one place for simplicity. I'd only confuse you more if I tried to describe a better way, so I'll make a working example in C++/CLI and send that to you. -- modified at 22:39 Monday 13th August, 2007 To be a little clearer and more correct, here's the form class with irrelevant stuff stripped out:
#include "WorkerClass.h"
namespace WinApp1
{
public ref class Form1 : public Form
{
public:
Form1()
{
InitializeComponent();
workerClass\_ = gcnew WorkerClass();
workerClass\_->OnUpdateText += gcnew UpdateText( this, &Form1::UpdateTextHandler );
}
private:
TextBox^ textBox\_;
Button^ button\_;
WorkerClass^ workerClass\_;
void button\_\_Click( System::Object^ sender, System::EventArgs^ e )
{
workerClass\_->DoSomething();
}
void UpdateTextHandler( String^ text )
{
textBox\_->Text = text;
}
};
}
And, in another file called WorkerClass.h, here's WorkerClass
, which was SomeClass
in my previous example:
namespace WinApp1
{
delegate void UpdateText( String^ );
ref class WorkerClass
{
public:
event UpdateText^ OnUpdateText;
void DoSomething()
{
++serialNumber\_;
OnUpdateText( Convert::ToString( serialNumber\_ ) );
}
private:
int serialNumber\_;
};
}
You don't need to derive your class from WorkerClass
. All you need is an event
of type UpdateText^
to which Form1
can attach a handler.