在 Windows 窗体控件中定义事件
有关定义自定义事件的详细信息,请参阅事件。 如果你定义的事件没有任何关联的数据,则使用事件数据的基类型 EventArgs,并使用 EventHandler 作为事件委托。 剩下的工作就是定义一个事件成员和一个引发该事件的受保护的 On
EventName 方法。
以下代码段显示了 FlashTrackBar
自定义控件如何定义自定义事件 ValueChanged
。 有关 FlashTrackBar
示例的完整代码,请参阅如何:创建显示进度的 Windows 窗体控件。
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
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)
{
onValueChanged?.Invoke(this, e);
}
}