在 Windows 窗体控件中定义事件

更新:2007 年 11 月

有关定义自定义事件的详细信息,请参见 引发事件。如果您定义的事件没有任何关联的数据,则使用事件数据的基类型 EventArgs,并使用 EventHandler 作为事件委托。剩下的工作就是定义一个事件成员和一个引发该事件的受保护的 On事件名称 方法。

以下代码片段说明了 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) {
      if (ValueChanged != null) {
         ValueChanged(this, e);
      }
   }
}

请参见

概念

Windows 窗体控件中的事件

引发事件

其他资源

处理和引发事件