Event 陳述式Event Statement

宣告使用者定義的事件。Declares a user-defined event.

語法Syntax

[ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Event eventname[(parameterlist)] _  
[ Implements implementslist ]  
' -or-  
[ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Event eventname As delegatename _  
[ Implements implementslist ]  
' -or-  
 [ <attrlist> ] [ accessmodifier ] _  
[ Shared ] [ Shadows ] Custom Event eventname As delegatename _  
[ Implements implementslist ]  
   [ <attrlist> ] AddHandler(ByVal value As delegatename)  
      [ statements ]  
   End AddHandler  
   [ <attrlist> ] RemoveHandler(ByVal value As delegatename)  
      [ statements ]  
   End RemoveHandler  
   [ <attrlist> ] RaiseEvent(delegatesignature)  
      [ statements ]  
   End RaiseEvent  
End Event  

組件Parts

組件Part 描述Description
attrlist 選擇性。Optional. 套用至此事件的屬性清單。List of attributes that apply to this event. 以逗號分隔多個屬性。Multiple attributes are separated by commas. 您必須將括屬性清單角括弧 ("<"和">")。You must enclose the Attribute List in angle brackets ("<" and ">").
accessmodifier 選擇性。Optional. 指定哪些程式碼可以存取此事件。Specifies what code can access the event. 可以是下列其中一項:Can be one of the following:

- 公用— 任何可以存取宣告它的項目程式碼可以存取它。- Public—any code that can access the element that declares it can access it.
- 受保護的— 只有在其類別或衍生的類別中的程式碼可以存取它。- Protected—only code within its class or a derived class can access it.
- Friend— 只有在相同的組件中的程式碼可以存取它。- Friend—only code in the same assembly can access it.
- 私用— 只有在宣告它的項目中的程式碼可以存取它。- Private—only code in the element that declares it can access it.
- Protected Friend-只有事件的類別、 衍生的類別或相同組件中的程式碼可以存取它。- Protected Friend-only code in the event's class, a derived class, or the same assembly can access it.
- 私用受保護-只有在事件的類別或相同組件中的衍生的類別中的程式碼可以存取它。- Private Protected-only code in the event's class or a derived class in the same assembly can access it.
Shared 選擇性。Optional. 指定此事件與類別或結構的特定執行個體不相關。Specifies that this event is not associated with a specific instance of a class or structure.
Shadows 選擇性。Optional. 指出這個事件會在基底類別中重新宣告並隱藏相同名稱的程式設計項目,或一組多載項目。Indicates that this event redeclares and hides an identically named programming element, or set of overloaded elements, in a base class. 您可以使用任何其他類型遮蔽任何一種已宣告的項目。You can shadow any kind of declared element with any other kind.

無法從遮蔽項目的衍生類別內使用遮蔽的項目,除了從無法存取遮蔽項目的位置以外。A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing element is inaccessible. 例如,如果 Private 項目會遮蔽基底類別項目,沒有 Private 項目存取權限的程式碼會改為存取基底類別項目。For example, if a Private element shadows a base-class element, code that does not have permission to access the Private element accesses the base-class element instead.
eventname 必要項。Required. 事件的名稱;依照標準變數命名慣例。Name of the event; follows standard variable naming conventions.
parameterlist 選擇性。Optional. 本機變數清單,表示此事件的參數。List of local variables that represent the parameters of this event. 您必須將括參數清單括號括住。You must enclose the Parameter List in parentheses.
Implements 選擇性。Optional. 指出此事件會實作介面的事件。Indicates that this event implements an event of an interface.
implementslist 如果使用 Implements,則為必要項。Required if Implements is supplied. 實作之 Sub 程序的清單。List of Sub procedures being implemented. 以逗號分隔多個程序:Multiple procedures are separated by commas:

implementedprocedure [, implementedprocedure ...]implementedprocedure [ , implementedprocedure ... ]

每個 implementedprocedure 都具有下列語法和組件:Each implementedprocedure has the following syntax and parts:

interface.definednameinterface.definedname

- interface 必要。- interface - Required. 介面名稱,該介面實作包含類別或結構的此程序。Name of an interface that this procedure's containing class or structure is implementing.
- Definedname 必要。- Definedname - Required. 名稱,據以在 interface 中定義程序。Name by which the procedure is defined in interface. 不一定要與 name 相同,這是此程序用來實作已定義程序的名稱。This does not have to be the same as name, the name that this procedure is using to implement the defined procedure.
Custom 必要項。Required. 事件宣告為 Custom 必須定義自訂 AddHandlerRemoveHandlerRaiseEvent 存取子。Events declared as Custom must define custom AddHandler, RemoveHandler, and RaiseEvent accessors.
delegatename 選擇性。Optional. 委派的名稱,指定事件處理常式簽章。The name of a delegate that specifies the event-handler signature.
AddHandler 必要項。Required. 宣告 AddHandler 存取子,指定加入事件處理常式時要執行的陳述式,可以明確地使用 AddHandler 陳述式或隱含地使用 Handles 子句。Declares an AddHandler accessor, which specifies the statements to execute when an event handler is added, either explicitly by using the AddHandler statement or implicitly by using the Handles clause.
End AddHandler 必要項。Required. 終止 AddHandler 區塊。Terminates the AddHandler block.
value 必要項。Required. 參數名稱。Parameter name.
RemoveHandler 必要項。Required. 宣告 RemoveHandler 存取子,指定使用 RemoveHandler 陳述式移除事件處理常式時要執行的陳述式。Declares a RemoveHandler accessor, which specifies the statements to execute when an event handler is removed using the RemoveHandler statement.
End RemoveHandler 必要項。Required. 終止 RemoveHandler 區塊。Terminates the RemoveHandler block.
RaiseEvent 必要項。Required. 宣告 RaiseEvent 存取子,指定使用 RaiseEvent 陳述式引發事件處理常式時要執行的陳述式。Declares a RaiseEvent accessor, which specifies the statements to execute when the event is raised using the RaiseEvent statement. 一般而言,這樣會叫用 AddHandlerRemoveHandler 存取子所維護的委派。Typically, this invokes a list of delegates maintained by the AddHandler and RemoveHandler accessors.
End RaiseEvent 必要項。Required. 終止 RaiseEvent 區塊。Terminates the RaiseEvent block.
delegatesignature 必要項。Required. 參數的清單,符合 delegatename 委派所需的參數。List of parameters that matches the parameters required by the delegatename delegate. 您必須將括參數清單括號括住。You must enclose the Parameter List in parentheses.
statements 選擇性。Optional. 陳述式,包含 AddHandlerRemoveHandlerRaiseEvent 方法的內文。Statements that contain the bodies of the AddHandler, RemoveHandler, and RaiseEvent methods.
End Event 必要項。Required. 終止 Event 區塊。Terminates the Event block.

備註Remarks

一旦已經宣告事件,使用 RaiseEvent 陳述式來引發事件。Once the event has been declared, use the RaiseEvent statement to raise the event. 一般事件可能會如下列片段所示宣告和引發:A typical event might be declared and raised as shown in the following fragments:

Public Class EventSource
    ' Declare an event.
    Public Event LogonCompleted(ByVal UserName As String)
    Sub CauseEvent()
        ' Raise an event on successful logon.
        RaiseEvent LogonCompleted("AustinSteele")
    End Sub
End Class

注意

您可以宣告事件引數,就像宣告程序的引數一樣,但下列情況除外:事件不可擁有具名引數、ParamArray 引數或 Optional 引數。You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have named arguments, ParamArray arguments, or Optional arguments. 事件沒有傳回值。Events do not have return values.

若要處理事件,您必須使用 HandlesAddHandler 陳述式,建立它與事件處理常式副程式的關聯。To handle an event, you must associate it with an event handler subroutine using either the Handles or AddHandler statement. 副程式與事件的簽章必須相符。The signatures of the subroutine and the event must match. 若要處理共用的事件,您必須使用 AddHandler 陳述式。To handle a shared event, you must use the AddHandler statement.

您只能在模組層級使用 EventYou can use Event only at module level. 這表示宣告內容事件必須是類別、 結構、 模組或介面,而且不能是原始程式檔、 命名空間、 程序或區塊。This means the declaration context for an event must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

在大部分情況下,您可以使用本主題「語法」一節中的第一個語法來宣告事件。In most circumstances, you can use the first syntax in the Syntax section of this topic for declaring events. 不過,某些情況下需要您對詳細事件行為有更多掌控。However, some scenarios require that you have more control over the detailed behavior of the event. 本主題中「語法」一節中的最後一個語法使用 Custom 關鍵字,藉由讓您定義自訂事件以提供控制權。The last syntax in the Syntax section of this topic, which uses the Custom keyword, provides that control by enabling you to define custom events. 在自訂事件中,您完整指定當程式碼於事件中加入或移除事件處理常式,或是當程式碼引發事件時,會發生什麼情況。In a custom event, you specify exactly what occurs when code adds or removes an event handler to or from the event, or when code raises the event. 如需範例,請參閱如何:宣告自訂事件以節省記憶體How to:宣告自訂事件以避免封鎖For examples, see How to: Declare Custom Events To Conserve Memory and How to: Declare Custom Events To Avoid Blocking.

範例Example

下列範例會使用事件以從 10 秒到 0 秒倒數計時。The following example uses events to count down seconds from 10 to 0. 程式碼會說明數個事件相關的方法、屬性和陳述式。The code illustrates several of the event-related methods, properties, and statements. 包括 RaiseEvent 陳述式。This includes the RaiseEvent statement.

引發事件的類別是事件來源,處理事件的方法為事件處理常式。The class that raises an event is the event source, and the methods that process the event are the event handlers. 事件來源對於它所產生的事件可以有多個處理常式。An event source can have multiple handlers for the events it generates. 當類別引發事件時,該事件是在每個類別 (已被選擇來處理該物件執行個體的事件) 上引發。When the class raises the event, that event is raised on every class that has elected to handle events for that instance of the object.

此範例也會使用表單 (Form1) 與按鈕 (Button1) 和文字方塊 (TextBox1)。The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). 當您按一下按鈕時時,第一個文字方塊會顯示從 10 秒到 0 秒的倒數計時。When you click the button, the first text box displays a countdown from 10 to 0 seconds. 在經過完整時間 (10 秒) 之後,第一個文字方塊會顯示 [完成]。When the full time (10 seconds) has elapsed, the first text box displays "Done".

Form1 的程式碼會指定表單的初始和終止狀態。The code for Form1 specifies the initial and terminal states of the form. 它也包含引發事件時執行的程式碼。It also contains the code executed when events are raised.

若要使用此範例,請建立新的 Windows Form 專案。To use this example, open a new Windows Forms project. 然後新增一個名為 Button1 的按鈕,和名為 TextBox1 的文字方塊到名為 Form1 的主表單中。Then add a button named Button1 and a text box named TextBox1 to the main form, named Form1. 然後以滑鼠右鍵按一下表單,並按一下檢視程式碼程式碼編輯器開啟。Then right-click the form and click View Code to open the code editor.

WithEvents 變數加入至 Form1 類別的宣告區段:Add a WithEvents variable to the declarations section of the Form1 class:

Private WithEvents mText As TimerState

將下列程式碼加入至 Form1 的程式碼。Add the following code to the code for Form1. 取代可能存在的任何重複程序,例如 Form_LoadButton_ClickReplace any duplicate procedures that may exist, such as Form_Load or Button_Click.

Private Sub Form1_Load() Handles MyBase.Load
    Button1.Text = "Start"
    mText = New TimerState
End Sub
Private Sub Button1_Click() Handles Button1.Click
    mText.StartCountdown(10.0, 0.1)
End Sub

Private Sub mText_ChangeText() Handles mText.Finished
    TextBox1.Text = "Done"
End Sub

Private Sub mText_UpdateTime(ByVal Countdown As Double
  ) Handles mText.UpdateTime

    TextBox1.Text = Format(Countdown, "##0.0")
    ' Use DoEvents to allow the display to refresh.
    My.Application.DoEvents()
End Sub

Class TimerState
    Public Event UpdateTime(ByVal Countdown As Double)
    Public Event Finished()
    Public Sub StartCountdown(ByVal Duration As Double, 
                              ByVal Increment As Double)
        Dim Start As Double = DateAndTime.Timer
        Dim ElapsedTime As Double = 0

        Dim SoFar As Double = 0
        Do While ElapsedTime < Duration
            If ElapsedTime > SoFar + Increment Then
                SoFar += Increment
                RaiseEvent UpdateTime(Duration - SoFar)
            End If
            ElapsedTime = DateAndTime.Timer - Start
        Loop
        RaiseEvent Finished()
    End Sub
End Class

按 F5 以執行上述範例中,並按一下 [] 按鈕啟動Press F5 to run the previous example, and click the button labeled Start. 第一個文字方塊會開始倒數計時。The first text box starts to count down the seconds. 在經過完整時間 (10 秒) 之後,第一個文字方塊會顯示 [完成]。When the full time (10 seconds) has elapsed, the first text box displays "Done".

注意

My.Application.DoEvents 方法不會以與表單相同的方式處理事件。The My.Application.DoEvents method does not process events in the same way the form does. 若要啟用表單以直接處理事件,您可以使用多執行緒。To enable the form to handle the events directly, you can use multithreading. 如需詳細資訊,請參閱 < Managed 執行緒處理For more information, see Managed Threading.

另請參閱See also