Definizione di un evento nei controlli Windows Form

Per informazioni dettagliate sulla definizione di eventi personalizzati, vedere Eventi. Se si definisce un evento che non presenta dati associati, usare il tipo base per i dati dell'evento, EventArgs, e usare EventHandler come delegato dell'evento. Tutto ciò che rimane da fare consiste nel definire un membro dell'evento e un metodo EventName protetto Onche genera l'evento.

Il frammento di codice seguente illustra come il controllo personalizzato FlashTrackBar definisce un evento personalizzato, ValueChanged. Per il codice completo per l'esempioFlashTrackBar, vedere Procedura: Creare un controllo Windows Form che mostra lo stato di avanzamento.

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

Vedi anche