The button which we can create on the form is written in terms of event handler in Form1.Designer.cs as
this.button1.Click += new System.EventHandler(this.button1_Click);
Here Click is public event EventHandler 's type and this EventHandler is a delegate as
public delegate void EventHandler(object sender, EventArgs e);
Now,
why can't it be '='(equals)
this.button1.Click = new System.EventHandler(this.button1_Click);
and also when I am passing the argument this.button1_Click, how does it match up to
void EventHandler(object sender, EventArgs e); delegate ? As here I have two arguments.
Please clear me with this.
Thank you
ttSo, let's see what event is.
Code, you are write
public event EventHandler MyEvent;
will compile to
private EventHandler MyEvent = null;
[MethodImp(MethodImplOptions.Synchronized)]
public void add_MyEvent(EventHandler value) {
MyEvent = (EventHandler)Delegate.Combine(MyEvent, value);
}
[MethodImp(MethodImplOptions.Synchronized)]
public void remove_MyEvent(EventHandler<NewMailEventArgs> value) {
MyEvent = (EventHandler)Delegate.Remove(MyEvent, value);
}
So, as you see, you cannot directly access to delegate and can only call += and -=, which is overridden for event class.
Also you can manually manage this mechanism by overriding methods += and -=.
You can do it like this:
public event EventHandler MyEvent
{
add { //your code for += here }
remove { //your code for -= here }
}
More about event and delegates you can read in book "CLR via C#". I found all of this in this book.
esentially, you are adding a handler to the event, not setting the one handler. you might want to have more handlers for an event. one handler should not preclude having other handlers because there might be multiple actions that you could want to take place in response to a single event that might happen in different classes and in different places and on different threads and under different conditions. += says make me a subscriber to this event (and potentially one subscriber among many).
What if you want to have multiple methods called on Click event. What you are doing with
this.button1.Click += new System.EventHandler(this.button1_Click);
is registering for this.button1_Click method to be invoked when Click event is raised. += adds handler and NOT assigns handler.
1/ it can not be '='(equals) because delegate is like a function pointer
2/ If you want to pass parameter to event button click, you have to make your own button class and implement Click event and have you own EventArgs
sample code:
public class MyEventArg
{
int _param1;
string _param2;
//you can add more param
public MyEventArg(int _param1,string _param2)
{
this._param1 = _param1;
this._param2 = _param2;
}
}
public delegate void MyButtonClickHandler(object sender, MyEventArg e)
public class MyButton:Control
{
public event MyButtonClickHandler OnMyClick;
//You can raise your event here
protected override void OnClick(EventArgs e)
{
MyEventArg e = new MyEventArg(1,"a");//just sample data here
this.OnMyClick(this,e);
}
}
In the form that contains MyButton class instant
public partial class Form1 : Form
{
MyButton myButton = new MyButton();
public Form1()
{
InitializeComponent();
myButton.OnMyClick += new MyButtonClickHandler(this.myButton_OnMyClicked);
}
private void myButton_OnMyClicked(object sender, MyEventArg e){
//your implementation
}
}
Dear Nagaraj Tantri,
For question 1: As said above, Due to Delegate can set up multi-event.
For question 2:As culithay said, if you want to pass custom arguments throug event buttion
click, if you want to use EventHandler and pass cutom own argument
you have to custom your control class and custom own event argument,
the custom event parameter CustomEventArg should inherit EventArg class.
You can take the sample code as below.
// Customs ColorChanged's event parameter.
public class ColorChangedEventArgs : EventArgs
{
private Color color;
public ColorChangedEventArgs(Color c)
{
color = c;
}
public Color GetColor
{
get { return color; }
}
}
//Add this method in your custom control
protected void ibtnTest_Click(object sender, ColorChangedEventArgs e)
{
//TODO;
}
You can also referen MSDN here
Related
What would be the equivalent C# code against following VB.Net code:
Public Event EndOfVideo()
Private Sub RaiseEndOfVideo()
RaiseEvent EndOfVideo()
End Sub
EDIT
Here is the equivalent C# code that telerik converter generated for me.
public event EndOfVideoEventHandler EndOfVideo;
public delegate void EndOfVideoEventHandler();
private void RaiseEndOfVideo()
{
if (EndOfVideo != null) {
EndOfVideo();
}
}
Calling RaiseEndOfVideo doesn't trigger/invoke EndOfVideo event, and Null Reference Exception is raised.
Consider you have class VideoPlayer which has event EndOfVideo and you want to raise this event and when someone calls method EndVideo on object of VideoPlayer.
Now, like any other member of a class event also initialized to null and gets the value when some handler is attached to it.
Attaching an handler to an event happens using += operator.
public class VideoPlayer
{
public event EndOfVideoEventHandler EndOfVideo;
// Following delegate indicates that the a method accepting no parameter
// and returning void can be attached as an handler to this event.
public delegate void EndOfVideoEventHandler();
public void EndVideo()
{
RaiseEndOfVideo();
}
private void RaiseEndOfVideo()
{
if (EndOfVideo != null)
{
// Following line of code executes the event handler which is
// attached to the event.
EndOfVideo();
}
}
}
public class WebPage
{
public void VideoStopped()
{
Console.WriteLine("Video Stopped");
}
}
Now in Main method of program.cs
static void Main(string[] args)
{
VideoPlayer player = new VideoPlayer();
WebPage page = new WebPage();
player.EndOfVideo += page.VideoStopped;
// Following method call on player object will call internally
// RaiseEndOfVideo which will Raise event and event will execute
// VideoStopped method of page object which is attached in previous line
// and display "Video Stopped" message in Console.
player.EndVideo();
Console.WriteLine("Completed!!! Press any key to exit");
Console.ReadKey();
}
I hope this would help you start understanding how events and delegates work in C#. For further reading you can go thru https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx
This is the generally accepted way to write an event with no parameters:
public class Foo
{
public event EventHandler EndOfVideo;
protected virtual void OnEndOfVideo()
{
var handler = EndOfVideo;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
Your code is what was needed in the old days: creating a delegate and yada yada.
To state the obvious, though, you need to subscribe to an event with something like:
public class Bar
{
public void DoAllTheThings()
{
var foo = new Foo();
foo.EndOfVideo += foo_EndOfVideo;
}
void foo_EndOfVideo(object sender, EventArgs e)
{
Console.WriteLine("EndOfVideo");
}
}
For the sake of completeness, the EventHandler delegate has a generic counterpart, EventHandler<T>, which you would use when you want an event that does have parameters, where T should be a class inheriting from System.EventArgs which holds the information you want your event to expose.
To do that, you will need to create a custom eventHandler to specify the method signatures of the handlers for your event
I have problem with event. For example let i have event
public event EventHandler<AxisChangedEventArgs> AxisChanged
which fires when Axis pan or zoom or something else. When it's firing i am making Console.WriteLine("Working");. How can i pass CFDBOX parameter into SomeWork anonymous method does not help because it will be imposible to unsubscribe from it. And i cannot override AxisChanged event.
public void AddEvents(CFDBOX CFDBOX) {
CFDBOX.PlotModel.Axes[0].AxisChanged += SomeWork;
}
public void RemoveEvents(CFDBOX CFDBOX) {
CFDBOX.PlotModel.Axes[0].AxisChanged -= SomeWork;
}
public EventHandler<AxisChangedEventArgs> SomeWork =
delegate(object o, AxisChangedEventArgs args) {
Console.WriteLine("Working");
}
;
Take advantage of closure lambda expressions:
private EventHandler<AxisChangedEventArgs> axisChangedEventHandler;
public void AddEvent(CFDBOX CFDBOX) {
// keep a reference of the event handler to remove it later
axisChangedEventHandler = (o, args) => {
// parameter CFDBOX bound to the event handler
Console.WriteLine("Working " + CFDBOX);
};
// register event handler
CFDBOX.PlotModel.Axes[0].AxisChanged += axisChangedEventHandler;
}
public void RemoveEvent() {
// unregister event handler
CFDBOX.PlotModel.Axes[0].AxisChanged -= axisChangedEventHandler;
}
Any parameter which must be passed with an event should be a member of your EventArgs implementation. In your scenario: AxisChangedEventArgs. Hope i get your question.
The sender of the event (in your case o) should always be the instance, which calls the event. So if your event get's fired from different classes (not instances!), you will have to check for the type of o.
Please forgive my little knowledge!
I have the following class in HIDNewDeviceEventMonitor.cs:
public class HIDNewDeviceEventMonitor : IDisposable
{
// used for monitoring plugging and unplugging of USB devices.
private ManagementEventWatcher watcherAttach;
public HIDNewDeviceEventMonitor()
{
// Catch USB HID plugged instance event watching
watcherAttach = new ManagementEventWatcher();
watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcherAttach.Query = new WqlEventQuery(#"SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PNPEntity' AND TargetInstance.DeviceID LIKE 'HID\\VID_04D8%'");
watcherAttach.Start();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("my device is inserted..");
}
public void Dispose()
{
watcherAttach.Stop();
watcherAttach.Dispose();
}
~HIDNewDeviceEventMonitor()
{
this.Dispose();
}
}
Now, how can I change this class to be able to add an event handler that the class can call from within watcher_EventArrived where someNewEvent is outside the class file, actually in the form.cs:
// code in the form
HIDNewDeviceEventMonitor ok = new HIDNewDeviceEventMonitor();
ok.Inserted += someNewEvent; // <-- my problem, I don't know how to add an event to the class this way
private void someNewEvent()
{
//Enumerate and add to listbox1
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ok.Dispose();
}
I 've seen this thing with other classes, how can I make my class like that?
Your Inserted event should look like this:
public event EventHandler Inserted;
You invoke it like this:
private void OnInserted()
{
if (this.Inserted != null)
{
this.Inserted(this, EventArgs.Empty);
}
}
The signature for the event handler is this:
void someNewEvent(object sender, EventArgs e)
{
//
}
Then you should wrap that code in the constructor of the class:
HIDNewDeviceEventMonitor ok;
public ClassName()
{
ok = new HIDNewDeviceEventMonitor();
ok.Inserted += someNewEvent; // <-- my problem
}
Declare the ok variable outside the constructor, and instantiate it inside. Then add the event handler.
Pro tip: You could use the generic EventHandler<T> if you need to supply a custom implementation of e.
Simply put, you're trying to add events to your HIDNewDeviceMonitor class.
To do this, first you'll need to define a delegate.
public delegate void InsertedHandler;
Next, you'll need to define the event in your HIDNewDeviceMonitor class.
// Notice how the event uses the delegate that's been defined
// v
public event InsertedHandler Inserted;
Now you'll need something that "fires" the event, which could easily be put in your watcher_EventArrived method.
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
Debug.WriteLine("my device is inserted..");
// Notice how we check the event handler for null.
// If you don't, it could throw a NullReferenceException.
// Irritating, but easy to debug.. Usually..
if (Inserted != null)
Inserted(); // Or whatever parameters you need.
}
We're all done with the HIDNewDeviceMonitor class.
Now whatever class that uses the HIDNewDeviceMonitor can use the EventHandler code that you provided.
However, it'll have to be the same delegate.
public class MyClass
{
HIDNewDeviceMonitor monitor;
public MyClass()
{
monitor = new HIDNewDeviceMonitor();
monitor.Inserted += DeviceInserted;
}
private void DeviceInserted()
{
// Execute code here
}
}
You need to do following in the HIDNewDeviceEventMonitor class:
1.) First define a public event inside the class like this-
public event EventHandler Inserted;
2.) Then fire this event within the code where you detect the changes in events. Like this-
if(Inserted != null)
Inserted(this,null);
The if condition checks if the event is registered by any listener. It's fired in case it is.
Hope this helps.
I have a custom checkbox control that inherited from System.Windows.Forms.Control
and it hasn't CheckedChanged event. I want to implement CheckedChange same as dot net native CheckBox. How can I do it well ?
You are inheriting fromn Control, not CheckBox, so the solution is similar to the one proposed by Frigik, but it's not exactly that one.
First of all you have to define the event in your class, i.e.:
public event EventHandler CheckedChanged;
In this way every developer using your control can subscribe/unsubscribe to the event. This is not enough, since the event will never be triggered. To do so, you have to define a method to trigger it, and the call this method whenever the state of your control changes:
private void RaiseCheckedChanged()
{
if (CheckedChanged!= null)
CheckedChanged(this, EventArgs.Empty);
}
Where this method will be called depends on the structure of your control. For instance if you have a property Checked, you could call the method in its setter:
public bool Checked
{
get { return _checked; }
set
{
_checked = value;
RaiseCheckedChanged();
}
}
Try this code :
CheckBox chkList1 = new CheckBox();
chkList1.CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
// Do your stuff
}
Try this:
public class YourCheckBox:CheckBox
{
public event EventHandler<EventArgs> OnCheckedChangedCustom;
protected override void OnCheckedChanged(EventArgs e)
{
if (OnCheckedChangedCustom!=null)
{
OnCheckedChangedCustom(this, EventArgs.Empty);
}
base.OnCheckedChanged(e);
}
}
I am working a problem which is about delegate and event. I am a newbid in this aspect. I don't know how to call the event.
Would some tell me?
Thanks in advance.
Here is simple example to call event....
// event_keyword.cs
using System;
public delegate void MyDelegate(); // delegate declaration
public interface I
{
event MyDelegate MyEvent;
void FireAway();
}
public class MyClass: I
{
public event MyDelegate MyEvent;
public void FireAway()
{
if (MyEvent != null)
MyEvent();
}
}
public class MainClass
{
static private void f()
{
Console.WriteLine("This is called when the event fires.");
}
static public void Main ()
{
I i = new MyClass();
i.MyEvent += new MyDelegate(f);
i.FireAway();
}
}
There is Link which may helpful.
The event can be invoked in the class in which it is declared. First you'll usually want to check if your event is null.
if (MyEvent != null) MyEvent(this, new EventArgs());
The arguments you pass to the event will depend on the declaration of the event. To give you a little more background, an event is just a compiler trick. When an event such as
public event ChangedEventHandler Changed;
is compiled it will look like
protected ChangedEventHandler _change;
public ChangedEventHandler Change
{
add { _change += value; }
remove { _change -= value; }
}
so anything inside where it is declared will use _change, while anything outside will use Change. In other words, inside where it is declared, it is just a delegate, and all the normal rules apply.
To resuse the event you just need to attach event with the you control for example .
buttonone.Click+= event1;
buttonTwo.Click+= event1;
Fore more details have look : C# Event Implementation Fundamentals, Best Practices and Conventions
Once you have defined the delegate, you need to define when to call the event. I mean you can call the event at assignment of any value to the specific variable.
here is the example of defining the delegate with the same variable class.
public class callbackdel : EventArgs
{
public readonly string resp = null;
public callbackdel(string s)
{
resp = s;
}
}
public delegate void WorkerEndHandler(object o, callbackdel e);
Now in the control you are using, you need to add this method.
public void OnWorkEnd(object o, callbackdel e)
{
WorkEnd(o, e);
}
after creating method and defining the delegate, you can fire the event from any of the delegate simply by calling the method.
OnWorkEnd((object)this, e);
When using an Event you first have to declare it:
// Create some custom arguments for the event
public class SampleEventArgs
{
public SampleEventArgs(string s)
{
Text = s;
}
public String Text {get; private set;}
}
// Define a class that uses the event
public class EventPublisher
{
// Declare the delegate
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
// Declare the event.
public event SampleEventHandler SampleEvent;
// Wrap the event in a protected virtual method
// to enable derived classes to raise the event.
protected virtual void RaiseSampleEvent()
{
// Raise the event by using the () operator.
if (SampleEvent != null)
SampleEvent(this, new SampleEventArgs("Hello"));
}
}
You can then subscribe to the event:
EventPublisher publisher = new EventPublisher();
publisher.SampleEvent += new EventPublisher.SampleEventHandler(SampleEventHandler);
public void SampleEventHandler(object sender, SampleEventArgs args)
{
}
Your event handler will be called when EventPublisher executes RaiseSampleEvent()