Dela via


Definiera en händelse i Windows Forms-kontroller

Mer information om hur du definierar anpassade händelser finns i Händelser. Om du definierar en händelse som inte har några associerade data använder du bastypen för händelsedata, EventArgsoch använder EventHandler som händelsedelegat. Allt som återstår att göra är att definiera en händelsemedlem och en skyddad OnEventName- metod som genererar händelsen.

Följande kodfragment visar hur den anpassade FlashTrackBar-kontrollen definierar en anpassad händelse, ValueChanged. Fullständig kod för -exemplet finns i How to: Create a Windows Forms Control That Shows Progress( Skapa en Windows-formulärkontroll som visar förlopp.

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

Se även