Here's a sample EventsManger class. All it does is check to see if there are any listeners for registered events. As you can see it's very simple.
public class EventsManager
{
public delegate void EventHandler(Object sender);
public event EventHandler EventsHolder;
protected virtual void OnEventOccurred()
{
if(EventsHolder != null) //meaning there is a listener for the event somewhere
EventsHolder(this);
}
public void EventWasFired()
{
OnEventOccurred();
}
}
I prefer to have my entry point in a class called driver (I'm used to C++) so I declare the following...
public class driver
{
//declare an events manager variable, make it public static so you can query it from all classes in your
//namespace
public static EventsManager em;
static void Main()
{
em = new EventsManager();
Application.Run(new Form1());
}
}
To test it, I created a user control with a button on it. i.e. a composite control. Now, I want that when I press the button, the user control back color turns red, ie, the button_click event gets bubbled up to the parent control so to speak. To make things easy, you can make your user control take an EventsManager as a constructor paramater.Then register a listener like so...
public UserControl1(EventsManager em)
{
InitializeComponent();
em.EventsHolder += new EventsManager.EventHandler(ButtonWasPressed);
}
private void ButtonWasPressed(Object sender)
{
this.BackColor = Color.Red;
}
You can then fire the event from the button's OnClick event like so
private void button1_Click(object sender, System.EventArgs e)
{
driver.em.EventWasFired();
}
You'll notice that I don't use EventArgs in my delegate declaration. I left that out because it's of no real use here. But it's advisable fro you to do this. (I typically derive a class from EventArgs and stuff it with mty own event specific code) Well it's ugly but it works for me, hope it helps Just another wannabe code junky