Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you trigger an event across classes?

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...
    }
}
like image 841
PICyourBrain Avatar asked Feb 22 '10 20:02

PICyourBrain


1 Answers

You cannot do this. Events can only be raised from within the class that declares the event.

Typically, you'd add a method on your class to raise the event, and call the method:

public class ClassLibrary 
{ 
    public event EventHandler DeviceAttached; 
    public void NotifyDeviceAttached()
    {
       // Do processing and raise event
     }

Then, in your other code, you'd just call myCL.NotifyDeviceAttached();

like image 112
Reed Copsey Avatar answered Nov 15 '22 08:11

Reed Copsey