Defining an Event
For details about defining custom events, see Raising an Event. If you define an event that does not have any associated data, use the base type for event data, System.ComponentModel.EventArgs, and use System.ComponentModel.EventHandler as the event delegate. All that remains to do is to define an event member and a protected OnEventName method that raises the event.
The following code fragment shows how the FlashTrackBar
custom control defines a custom event, ValueChanged
. For the complete code for the FlashTrackBar
sample, see the Windows Forms Control Sample.
Option Explicit
Option Strict
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Public Class FlashTrackBar
Inherits Control
' The event does not have any data, so EventHandler is adequate
' as the event delegate.
' Define the event member using the event keyword.
' In this case, for efficiency, the event is defined
' using the event property construct.
Public Event ValueChanged As EventHandler
' The protected method that raises the ValueChanged
' event when the value has actually
' changed. Derived controls can override this method.
Protected Overridable Sub OnValueChanged(e As EventArgs)
RaiseEvent ValueChanged(Me, e)
End Sub
End Class
[C#]using System;
using System.Windows.Forms;
using System.Drawing;
public class FlashTrackBar : Control {
// The event does not have any data, so EventHandler is adequate
// as the event delegate.
private EventHandler onValueChanged;
// Define the event member using the event keyword.
// In this case, for efficiency, the event is defined
// using the event property construct.
public event EventHandler ValueChanged {
add {
onValueChanged += value;
}
remove {
onValueChanged -= value;
}
}
// The protected method that raises the ValueChanged
// event when the value has actually
// changed. Derived controls can override this method.
protected virtual void OnValueChanged(EventArgs e) {
if (ValueChanged != null) {
ValueChanged(this, e);
}
}
}
See Also
Events in Windows Forms Controls | Raising an Event | Handling and Raising Events