Compartilhar via


Definir um evento no Windows Forms Controls

Para obter detalhes sobre como definir eventos personalizados, consulte Gerando um evento. Se você definir um evento que não tem qualquer dado associado, use o tipo de base para dados de eventos, EventArgse usar EventHandler sistema autônomo o delegado do evento. Tudo o que resta a fazer é definir um membro do evento e um protegido OnEventName método dispara o evento.

O código a seguir fragmento mostra como a FlashTrackBar controle personalizado define um evento personalizado, ValueChanged. Para o código completo para o FlashTrackBar exemplo, consulte o Como: Criar um controle Windows Forms que mostra o andamento.

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

Consulte também

Conceitos

Eventos em controles Windows Forms

Gerando um evento

Outros recursos

Tratamento e disparada de eventos