Windows フォーム コントロールのイベントの定義

カスタム イベントの定義方法の詳細については、イベントに関するページを参照してください。 関連データがないイベントを定義する場合、イベント データの基本型である EventArgs を使用し、イベント デリゲートとして EventHandler を使用します。 あとは、イベント メンバーを定義し、イベントを発生させる OnEventName プロテクト メソッドを定義するだけです。

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);  
   }  
}  

関連項目