views:

29

answers:

1

I am writing a Class Library that will be used by other applications. I am writing it in C#.NET. I am having a problem with triggering events across classes. Here is what I need to do...

public class ClassLibrary
{
    public event EventHandler DeviceAttached;

    public ClassLibrary()
    {
        // do some stuff
        OtherClass.Start();
    }
}

public class OtherClass : Form
{
    public Start()
    {
        // do things here to initialize receiving messages
    }

    protected override void WndProc (ref message m)
    {
       if (....)
       {
          // THIS IS WHERE I WANT TO TRIGGER THE DEVICE ATTACHED EVENT IN ClassLibrary
          // I can't seem to access the eventhandler here to trigger it.
          // How do I do it?

       }
       base.WndProc(ref m);
    }

}

Then in the application that is using the class library I will do this...

public class ClientApplication
{
    void main()
    {
       ClassLibrary myCL = new ClassLibrary();
       myCL.DeviceAttached += new EventHandler(myCl_deviceAttached);
    }

    void myCl_deviceAttached(object sender, EventArgs e)
    {
         //do stuff...
    }
}
+1  A: 

Probably the easiest option is to add a method to ClassLibrary which raises the event...i.e.

internal void RaiseDeviceAttached(object sender, EventArgs e)
{
  if (DeviceAttached != null) DeviceAttached(sender, e);
}

Then, in OtherClass, simply call that method of ClassLibrary.

Another option is to go down the reflection route to trigger the event.

Andy Whitfield