Can a custom event be created for any object method?
To do this do I just use the following syntax?:
myObject.myMethod +=new EventHandler(myNameEvent);
The following code has prompted this question:
private void btRunProcessAndRefresh_Click(object sender,EventArgs e) { myProcess =new Process(); myProcess.StartInfo.FileName = @"c:\ConsoleApplication4.exe"; myProcess.Exited += new EventHandler(MyProcessExited); myProcess.EnableRaisingEvents =true; myProcess.SynchronizingObject =this; btRunProcessAndRefresh.Enabled =false; myProcess.Start(); }
A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.
Why using custom events. The custom events allow you to decouple the code that you want to execute after another piece of code completes. For example, you can separate the event listeners in a separate script. In addition, you can have multiple event listeners to the same custom event.
Declare the class containing the event:
class MyClass { public event EventHandler MyEvent; public void Method() { OnEvent(); } private void OnEvent() { if (MyEvent != null) { MyEvent(this, EventArgs.Empty); } } }
Use it like this:
MyClass myObject = new MyClass(); myObject.MyEvent += new EventHandler(myObject_MyEvent); myObject.Method();
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