Have you ever wanted your own event? Something to occur when something happens? Well, Today I will be showing you how to do just that. Lets get to it!
You will need knowledge of Delegate voids, Event calling / throwing, some basic skills.
Section 1 - Ready your project.
I will be using a custom control for this, so I will need my Windows Forms Project and a class library.
In your class library, Add these references:
System.Windows.Forms
System.Drawing
System.ComponentModel
System.Diagnostics
System.Runtime
You don't need all of them, but you might want to add those references so you don't get lost somewhere.
Add your Class library as a reference for Form1. This will make it easier to access and edit our control from a different project.
Now let's inherit a control for our class library.
Code: Select all
namespace Event
{
public class CustomControl : Control
{
}
}
Create these regions:
Regions
Events
Properties
Constructor
Methods
Code: Select all
public class CustomControl : Control
{
#region Regions
#endregion
#region Events
#endregion
#region Properties
#endregion
#region Constructor
#endregion
#region Methods
#endregion
}
Section 2 - Declaring our Event
In the Events region, create these three regions:
Public Event Handlers
Public Events
Code: Select all
public class CustomControl : Control
{
Regions
#region Events
#region Public Event Handlers
#endregion
#region Public Events
#endregion
#endregion
Properties
Constructor
Methods
}
Under the Constructor Region type this
Code: Select all
public <ClassName>()
{
}
Code: Select all
public CustomControl()
{
}
In the Event Handler region type this.
Code: Select all
#region Public Event Handlers
//String being Used
public string NewString;
//Delegate Void
public delegate void StringChangedHandler(string StringText);
#endregion
Code: Select all
#region Public Events
//Public Event
public event StringChangedHandler StringChanged;
//Public String
public string TextString
{
get { return this.NewString; }
set
{
//Setting the String
this.NewString = value;
//Making sure it is not null
if (this.StringChanged != null)
{
//Setting the event
this.StringChanged(value);
}
}
}
#endregion
Please, download the Video Results. (I thought it would be easier to make a video.) Also, Download the Source!