Bagikan melalui


Menentukan Peristiwa di Kontrol Formulir Windows

Untuk detail tentang menentukan peristiwa kustom, lihat Peristiwa. Jika Anda menentukan peristiwa yang tidak memiliki data terkait, gunakan jenis dasar untuk data peristiwa, EventArgs, dan gunakan EventHandler sebagai delegasi peristiwa. Yang masih harus dilakukan adalah menentukan anggota peristiwa dan metode EventName yang dilindungi Onyang meningkatkan peristiwa.

Fragmen kode berikut menunjukkan bagaimana FlashTrackBar kontrol kustom menentukan peristiwa kustom, ValueChanged. Untuk kode lengkap untuk FlashTrackBar sampel, lihat Cara: Membuat Kontrol Formulir Windows yang Memperlihatkan Kemajuan.

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

Baca juga