How to Make My Own Event in C#

How can I make my own event in C#?

Here's an example of creating and using an event with C#

using System;

namespace Event_Example
{
//First we have to define a delegate that acts as a signature for the
//function that is ultimately called when the event is triggered.
//You will notice that the second parameter is of MyEventArgs type.
//This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);

//This is a class which describes the event to the class that recieves it.
//An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text)
{
EventInfo = Text;
}
public string GetInfo()
{
return EventInfo;
}
}

//This next class is the one which contains an event and triggers it
//once an action is performed. For example, lets trigger this event
//once a variable is incremented over a particular value. Notice the
//event uses the MyEventHandler delegate to create a signature
//for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get
{
return i;
}
set
{
if(value <= Maximum)
{
i = value;
}
else
{
//To make sure we only trigger the event if a handler is present
//we check the event to make sure it's not null.
if(OnMaximum != null)
{
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}

class Program
{
//This is the actual method that will be assigned to the event handler
//within the above class. This is where we perform an action once the
//event has been triggered.
static void MaximumReached(object source, MyEventArgs e)
{
Console.WriteLine(e.GetInfo());
}

static void Main(string[] args)
{
//Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);

for(int x = 0; x <= 15; x++)
{
MyObject.MyValue = x;
}

Console.ReadLine();
}
}
}

simple custom event

This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.

public partial class Form1 : Form
{
private TestClass _testClass;
public Form1()
{
InitializeComponent();
_testClass = new TestClass();
_testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
}

private void UpdateStatus(object sender, ProgressEventArgs e)
{
SetStatus(e.Status);
}

private void SetStatus(string status)
{
label1.Text = status;
}

private void button1_Click_1(object sender, EventArgs e)
{
TestClass.Func();
}

}

public class TestClass
{
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
public event StatusUpdateHandler OnUpdateStatus;

public static void Func()
{
//time consuming code
UpdateStatus(status);
// time consuming code
UpdateStatus(status);
}

private void UpdateStatus(string status)
{
// Make sure someone is listening to event
if (OnUpdateStatus == null) return;

ProgressEventArgs args = new ProgressEventArgs(status);
OnUpdateStatus(this, args);
}
}

public class ProgressEventArgs : EventArgs
{
public string Status { get; private set; }

public ProgressEventArgs(string status)
{
Status = status;
}
}

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(Metronome m, EventArgs e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
Tick(this, e);
}
}
}
}
public class Listener
{
public void Subscribe(Metronome m)
{
m.Tick += new Metronome.TickHandler(HeardIt);
}

private void HeardIt(Metronome m, EventArgs e)
{
System.Console.WriteLine("HEARD IT");
}
}
class Test
{
static void Main()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}

how to create my own event in c#?

1 You can implement a hander for an event of single click on a button. So, it will be executed each time the button is clicked. This handler will count the number of clicks and raise another event if there were 3 clicks.

int nClicks;
event EventHandler TrippleClick;

public Form1()
{
InitializeComponent();
this.button1.Click += new System.EventHandler(this.button1_Click);
nClicks = 0;
TrippleClick = new EventHandler(OnTrippleClick);
}

void OnTrippleClick(object sender, EventArgs e)
{
MessageBox.Show("Tripple click");
}

private void button1_Click(object sender, EventArgs e)
{
nClicks++;
if (nClicks == 3)
{
TrippleClick(sender, e);
nClicks = 0;
}
}

How to create a custom events in C#

I understand that you are trying to build a scheduler task like functionality in c#. Based on my understanding, a windows service would do the task for you like listening for the availability of internet and then performing the mail sending operation when the application goes online.

W.R.To Events, you can build your own event engine that the one that raises the application events when the app runs and then there will be database entries that lists the pending tasks. There will be a background job like a windows service that reads the database and based on the availability of internet or on some condition executes the job.

If you can be more clear on the exact use-case and what you have tried so far the community can help you better.

Sample
class Observable
{
public event ImageUploadeventHandler InternetcOnnected;

public void DoSomething()
{
ImageUploadeventHandler handler = InternetcOnnected;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
class Observer
{
public void HandleEvent(object sender, EventArgs args)
{
// upload the image to the online service
}
}

How to make own event handler?

If I am interpreting this correctly, there are two parts to this. First, you need to detect invalid values and throw exceptions. Second, you need to raise an event when the property changes. This can be achieved as follows.

private float mass;
public float Mass
{
get
{
return this.mass;
}

set
{
if (value <= 0.0F)
{
throw new ArgumentOutOfRangeException("Mass cannot be zero or negative.");
}

if (this.mass != value)
{
this.mass = value;
OnMassChanged(EventArgs.Empty);
}
}
}

public event EventHandler MassChanged;

protected virtual void OnMassChanged(EventArgs args)
{
var handler = this.MassChanged;
if (handler != null)
{
handler(this, args);
}
}

To show a message if an invalid entry is made, you should put a try \ catch block around the call to set Mass and catch the ArgumentOutOfRangeException.

How to Create a Custom Event Handling class Like EventArgs

I'm not entirely sure what you mean, but if you're talking about an EventArgs derived class:

public class MyEventArgs : EventArgs
{
private string m_Data;
public MyEventArgs(string _myData)
{
m_Data = _myData;
} // eo ctor

public string Data {get{return m_Data} }
} // eo class MyEventArgs

public delegate void MyEventDelegate(MyEventArgs _args);

public class MySource
{
public void SomeFunction(string _data)
{
// raise event
if(OnMyEvent != null) // might not have handlers!
OnMyEvent(new MyEventArgs(_data));
} // eo SomeFunction
public event MyEventDelegate OnMyEvent;
} // eo class mySource

Hope this helps.

How To Create Custom Event in Main Form in C#?

You want a static class to be able to trigger your main form to update its list view via an event without specifically knowing about the main form, as I understand it. This is how I would do that:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SingletonA.GetInstance.MyEvent += UpdateListView;
}

private void UpdateListView(object sender, EventArgs e)
{
// Update your listview
}
}

//lazy initialization of singleton - not thread safe see http://www.dotnettricks.com/learn/designpatterns/singleton-design-pattern-dotnet for other thread safe version
public class SingletonA
{
private static SingletonA instance = null;
private SingletonA() { }

public event EventHandler<EventArgs> MyEvent;

void TellFormToUpdateListView()
{
MyEvent?.Invoke(typeof(SingletonA), EventArgs.Empty);
}

public static SingletonA GetInstance
{
get
{
if (instance == null)
instance = new SingletonA();

return instance;
}
}
}

how to create custom event for my property

Define an event as usual (it may be defined as routed event if it makes sense) and then register a dependency property callback where you raise this event. Something like this:

public event EventHandler ValueChanged;

public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}

public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(SpeedoMeter), new PropertyMetadata(0.0,
OnChanged,
OnCoerceValueChanged));

private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SpeedoMeter speedoMeter = (SpeedoMeter)d;
EventHandler handler = speedoMeter.ValueChanged;
if (handler != null)
{
handler(speedoMeter, EventArgs.Empty);
}
}

Obviously you may name your event and property whatever you want. If you have a Value property and want a ValueChanged event, you may for example derive from something like RangeBase or similar. This is just an example of how you would raise a custom event when a dependency property changes.



Related Topics



Leave a reply



Submit