Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Custom Event

Tags:

c#

events

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();     } 
like image 287
whytheq Avatar asked Mar 27 '12 07:03

whytheq


People also ask

How do you write a custom event?

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.

What is the purpose of custom events?

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.


1 Answers

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(); 
like image 186
ionden Avatar answered Sep 30 '22 12:09

ionden