定義 Windows Form 控制項中的事件
如需定義自訂事件的詳細資訊,請參閱引發事件。 如果您定義不含任何關聯資料的事件,請使用事件資料的基底型別 (Base Type) EventArgs,並使用 EventHandler 做為事件委派 (Delegate)。 剩下要做的事就是定義事件成員和引發事件的保護的 OnEventName 方法。
下列程式碼片段示範 FlashTrackBar 自訂控制項如何定義自訂事件 ValueChanged。 如需 FlashTrackBar 範例的完整程式碼,請參閱 HOW TO:建立顯示進度的 Windows Form 控制項。
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) {
if (ValueChanged != null) {
ValueChanged(this, e);
}
}
}