VB 版 (精华区)
发信人: student (earth), 信区: VB
标 题: 深入浅出VB.Net Windows Form-4
发信站: 哈工大紫丁香 (2002年01月26日19:19:12 星期六), 站内信件
事件响应
VB6及其以前的版本都是事件驱动,可以很容易写出响应事件的代码,举例而言,有一
个叫button1的button控件,你希望他响应用户点击事件,你所需要做的是建立一个butto
n1_click子程序(实际上VB_ide已经帮你做了),在VB.Net中也一样,一旦你将控件加入
设计模式,就可以点击它,告诉VB.Net你想写一个事件响应程序,在这里将显示怎样手工
写事件响应程序。
如果你希望对象响应一个事件,那么在你宣布变量时要使用关键字WithEvents,例如
,你想使你的按钮响应一个事件,原来的方式是:
Private Button1 As Button
现在要在变量名前加上关键字WithEvents,就像下面这段代码
Private WithEvents Button1 As Button
然后你需要为每个事件创建一个处理过程,这样你的控件才会响应它。对于button1响
应click事件需要写一个button1_click子程序,代码如下:
Private Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
'响应代码
End Sub
form类和所有控件类都继承control类的事件,在.Net Framework 索引中列出了Syst
em.Windows.Forms.Control类全部58个事件,包括继承自componentde 事件。常用的事件
有:Click, DoubleClick, GotFocus, LostFocus, KeyUp, KeyDown等等。
在list3的代码中创建了一个窗体并添加了两个控件:button控件和textbox控件,对
button1控件在宣布变量时使用关键字WithEvents,创建两个事件处理程序:Button1_Cli
ck 和 Button1_GotFocus
Listing 3:
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Private WithEvents Button1 As Button
Private WithEvents Button1 As Button
Private TextBox1 As TextBox
Public Sub New()
InitializeComponent()
End Sub
Private Sub InitializeComponent()
Me.Text = "Developer Form"
Me.Width = 400
Me.Height = 300
Button1 = New Button()
TextBox1 = New TextBox()
Button1.Left = 200
Button1.Top = 200
Button1.Width = 100
Button1.Height = 40
Button1.TabIndex = 0
Button1.Text = "Click Me"
TextBox1.Left = 200
TextBox1.Top = 30
TextBox1.Width = 150
TextBox1.Height = 40
Me.Controls.Add(Button1)
Me.Controls.Add(TextBox1)
End Sub
Private Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Ooops.... you clicked me."
End Sub
Private Sub Button1_GotFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.GotFocus
TextBox1.Text = "Button got focus."
End Sub
End Class
End Sub
End Class
--
※ 来源:·哈工大紫丁香 bbs.hit.edu.cn·[FROM: 202.118.236.168]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:2.844毫秒