Definir un evento en los controles de formularios Windows Forms

Para información detallada sobre cómo definir eventos personalizados, consulte Eventos. Si define un evento que no tiene datos asociados, use el tipo base de datos de evento, EventArgs, y use EventHandler como delegado de evento. Todo lo que queda por hacer es definir un miembro de evento y un método OnEventName protegido que genera el evento.

El fragmento de código siguiente muestra cómo el control personalizado FlashTrackBar define un evento personalizado ValueChanged. Para obtener el código fuente completo del ejemplo FlashTrackBar, consulte Procedimiento para crear un control de Windows Forms que muestre el progreso.

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

Consulte también