VB.Net - 事件处理

事件基本上是一个用户操作,如按键,点击,鼠标移动等,或某些事件,如系统生成的通知。 应用程序需要在事件发生时对其进行响应。

单击按钮,或在文本框中输入某些文本,或单击菜单项,都是事件的示例。 事件是调用函数或可能导致另一个事件的操作。


事件处理程序是指示如何响应事件的函数。

VB.Net是一种事件驱动的语言。 主要有两种类型的事件:


处理鼠标事件

鼠标事件发生与鼠标移动形式和控件。以下是与Control类相关的各种鼠标事件:

鼠标事件的事件处理程序获得一个类型为MouseEventArgs的参数。 MouseEventArgs对象用于处理鼠标事件。它具有以下属性:


示例

下面是一个例子,它展示了如何处理鼠标事件。执行以下步骤:

Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "tutorialspont.com"
   End Sub

   Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_
        Handles txtID.MouseEnter
      'code for handling mouse enter on ID textbox
      txtID.BackColor = Color.CornflowerBlue
      txtID.ForeColor = Color.White
   End Sub
   Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _
        Handles txtID.MouseLeave
      'code for handling mouse leave on ID textbox
      txtID.BackColor = Color.White
      txtID.ForeColor = Color.Blue
   End Sub
   Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _
       Handles txtName.MouseEnter
      'code for handling mouse enter on Name textbox
      txtName.BackColor = Color.CornflowerBlue
      txtName.ForeColor = Color.White
   End Sub
   Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _
      Handles txtName.MouseLeave
      'code for handling mouse leave on Name textbox
      txtName.BackColor = Color.White
      txtName.ForeColor = Color.Blue
   End Sub
   Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _
      Handles txtAddress.MouseEnter
      'code for handling mouse enter on Address textbox
      txtAddress.BackColor = Color.CornflowerBlue
      txtAddress.ForeColor = Color.White
   End Sub
   Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _
        Handles txtAddress.MouseLeave
      'code for handling mouse leave on Address textbox
      txtAddress.BackColor = Color.White
      txtAddress.ForeColor = Color.Blue
   End Sub

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
       Handles Button1.Click
      MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
   End Sub
End Class


当使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:


事件处理示例1

尝试在文本框中输入文字,并检查鼠标事件:


事件处理结果表


处理键盘事件

以下是与Control类相关的各种键盘事件:


KeyDown和KeyUp事件的事件处理程序获得一个类型为KeyEventArgs的参数。此对象具有以下属性:


KeyDown和KeyUp事件的事件处理程序获得一个类型为KeyEventArgs的参数。此对象具有以下属性:

示例

让我们继续前面的例子来说明如何处理键盘事件。 代码将验证用户为其客户ID和年龄输入一些数字。


当使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:


VB.Net事件示例


如果将age或ID的文本留空,或输入一些非数字数据,则会出现一个警告消息框,并清除相应的文本:


VB.Net事件示例