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...
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With