定義類(lèi)時(shí),可以為數據類(lèi)型定義藍圖。 這實(shí)際上并不定義任何數據,但它定義了類(lèi)名的含義,即類(lèi)的對象將包含什么以及可以對這樣的對象執行什么操作。
對象是類(lèi)的實(shí)例。 構成類(lèi)的方法和變量稱(chēng)為類(lèi)的成員。
類(lèi)的定義以關(guān)鍵字Class開(kāi)頭,后跟類(lèi)名稱(chēng); 和類(lèi)體,由End Class語(yǔ)句結束。 以下是類(lèi)定義的一般形式:
- [ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
- Class name [ ( Of typelist ) ]
- [ Inherits classname ]
- [ Implements interfacenames ]
- [ statements ]
- End Class
attributelist 屬性列表:is a list of attributes that apply to the class. Optional. attributelist是一個(gè)適用于類(lèi)的屬性列表。 可選的。
accessmodifier 訪(fǎng)問(wèn)修改器:defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional. accessmodifier定義類(lèi)的訪(fǎng)問(wèn)級別,它的值為 - Public,Protected,Friend,Protected Friend和Private。 可選的。
Shadows 陰影:indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional. 陰影表示變量在基類(lèi)中重新聲明和隱藏一個(gè)同名的元素或一組重載的元素。 可選的。
MustInherit:specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional. MustInherit指定該類(lèi)只能用作基類(lèi),并且不能直接從它創(chuàng )建對象,即抽象類(lèi)。 可選的。
NotInheritable 不可繼承:specifies that the class cannot be used as a base class. NotInheritable指定該類(lèi)不能用作基類(lèi)。
Partial 部分:indicates a partial definition of the class. Partial表示類(lèi)的部分定義。
Inherits 繼承:specifies the base class it is inheriting from. Inherits指定它繼承的基類(lèi)。
Implements 實(shí)現:specifies the interfaces the class is inheriting from. Implements指定類(lèi)繼承的接口。
下面的示例演示了一個(gè)Box類(lèi),它有三個(gè)數據成員,長(cháng)度,寬度和高度:
- Module mybox
- Class Box
- Public length As Double ' Length of a box
- Public breadth As Double ' Breadth of a box
- Public height As Double ' Height of a box
- End Class
- Sub Main()
- Dim Box1 As Box = New Box() ' Declare Box1 of type Box
- Dim Box2 As Box = New Box() ' Declare Box2 of type Box
- Dim volume As Double = 0.0 ' Store the volume of a box here
- ' box 1 specification
- Box1.height = 5.0
- Box1.length = 6.0
- Box1.breadth = 7.0
- ' box 2 specification
- Box2.height = 10.0
- Box2.length = 12.0
- Box2.breadth = 13.0
- 'volume of box 1
- volume = Box1.height * Box1.length * Box1.breadth
- Console.WriteLine('Volume of Box1 : {0}', volume)
- 'volume of box 2
- volume = Box2.height * Box2.length * Box2.breadth
- Console.WriteLine('Volume of Box2 : {0}', volume)
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Volume of Box1 : 210
- Volume of Box2 : 1560
類(lèi)的成員函數是一個(gè)函數,它的定義或其原型在類(lèi)定義中像任何其他變量一樣。 它對它所屬的類(lèi)的任何對象進(jìn)行操作,并且可以訪(fǎng)問(wèn)該對象的類(lèi)的所有成員。
成員變量是對象的屬性(從設計角度),它們被保持為私有以實(shí)現封裝。 這些變量只能使用public成員函數訪(fǎng)問(wèn)。
讓我們把上面的概念設置并獲得類(lèi)中不同類(lèi)成員的值:
- Module mybox
- Class Box
- Public length As Double ' Length of a box
- Public breadth As Double ' Breadth of a box
- Public height As Double ' Height of a box
- Public Sub setLength(ByVal len As Double)
- length = len
- End Sub
- Public Sub setBreadth(ByVal bre As Double)
- breadth = bre
- End Sub
- Public Sub setHeight(ByVal hei As Double)
- height = hei
- End Sub
- Public Function getVolume() As Double
- Return length * breadth * height
- End Function
- End Class
- Sub Main()
- Dim Box1 As Box = New Box() ' Declare Box1 of type Box
- Dim Box2 As Box = New Box() ' Declare Box2 of type Box
- Dim volume As Double = 0.0 ' Store the volume of a box here
- ' box 1 specification
- Box1.setLength(6.0)
- Box1.setBreadth(7.0)
- Box1.setHeight(5.0)
- 'box 2 specification
- Box2.setLength(12.0)
- Box2.setBreadth(13.0)
- Box2.setHeight(10.0)
- ' volume of box 1
- volume = Box1.getVolume()
- Console.WriteLine('Volume of Box1 : {0}', volume)
- 'volume of box 2
- volume = Box2.getVolume()
- Console.WriteLine('Volume of Box2 : {0}', volume)
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Volume of Box1 : 210
- Volume of Box2 : 1560
類(lèi)構造函數是每當我們創(chuàng )建該類(lèi)的新對象時(shí)執行的類(lèi)的特殊成員子類(lèi)。 構造函數具有名稱(chēng)New,并且沒(méi)有任何返回類(lèi)型。
下面的程序解釋了構造函數的概念:
- Class Line
- Private length As Double ' Length of a line
- Public Sub New() 'constructor
- Console.WriteLine('Object is being created')
- End Sub
- Public Sub setLength(ByVal len As Double)
- length = len
- End Sub
- Public Function getLength() As Double
- Return length
- End Function
- Shared Sub Main()
- Dim line As Line = New Line()
- 'set line length
- line.setLength(6.0)
- Console.WriteLine('Length of line : {0}', line.getLength())
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Object is being created
- Length of line : 6
默認構造函數沒(méi)有任何參數,但如果需要,構造函數可以有參數。 這樣的構造函數稱(chēng)為參數化構造函數。 此技術(shù)可幫助您在創(chuàng )建對象時(shí)為其分配初始值,如以下示例所示:
- Class Line
- Private length As Double ' Length of a line
- Public Sub New(ByVal len As Double) 'parameterised constructor
- Console.WriteLine('Object is being created, length = {0}', len)
- length = len
- End Sub
- Public Sub setLength(ByVal len As Double)
- length = len
- End Sub
- Public Function getLength() As Double
- Return length
- End Function
- Shared Sub Main()
- Dim line As Line = New Line(10.0)
- Console.WriteLine('Length of line set by constructor : {0}', line.getLength())
- 'set line length
- line.setLength(6.0)
- Console.WriteLine('Length of line set by setLength : {0}', line.getLength())
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Object is being created, length = 10
- Length of line set by constructor : 10
- Length of line set by setLength : 6
析構函數是一個(gè)類(lèi)的特殊成員Sub,只要它的類(lèi)的對象超出范圍,它就被執行。
析構函數名為Finalize,它既不能返回值也不能接受任何參數。 析構函數在釋放程序之前釋放資源非常有用,比如關(guān)閉文件,釋放內存等。
析構函數不能繼承或重載。
下面的例子解釋析構函數的概念:
- Class Line
- Private length As Double ' Length of a line
- Public Sub New() 'parameterised constructor
- Console.WriteLine('Object is being created')
- End Sub
- Protected Overrides Sub Finalize() ' destructor
- Console.WriteLine('Object is being deleted')
- End Sub
- Public Sub setLength(ByVal len As Double)
- length = len
- End Sub
- Public Function getLength() As Double
- Return length
- End Function
- Shared Sub Main()
- Dim line As Line = New Line()
- 'set line length
- line.setLength(6.0)
- Console.WriteLine('Length of line : {0}', line.getLength())
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Object is being created
- Length of line : 6
- Object is being deleted
我們可以使用Shared關(guān)鍵字將類(lèi)成員定義為靜態(tài)。 當我們將一個(gè)類(lèi)的成員聲明為Shared時(shí),意味著(zhù)無(wú)論創(chuàng )建多少個(gè)對象,該成員只有一個(gè)副本。
關(guān)鍵字“共享”意味著(zhù)類(lèi)只存在一個(gè)成員實(shí)例。 共享變量用于定義常量,因為它們的值可以通過(guò)調用類(lèi)而不創(chuàng )建它的實(shí)例來(lái)檢索。
共享變量可以在成員函數或類(lèi)定義之外初始化。 您還可以在類(lèi)定義中初始化共享變量。
您還可以將成員函數聲明為共享。 這樣的函數只能訪(fǎng)問(wèn)共享變量。 共享函數甚至在創(chuàng )建對象之前就存在。
以下示例演示了共享成員的使用:
- Class StaticVar
- Public Shared num As Integer
- Public Sub count()
- num = num + 1
- End Sub
- Public Shared Function getNum() As Integer
- Return num
- End Function
- Shared Sub Main()
- Dim s As StaticVar = New StaticVar()
- s.count()
- s.count()
- s.count()
- Console.WriteLine('Value of variable num: {0}', StaticVar.getNum())
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
Value of variable num: 3面向對象編程中最重要的概念之一是繼承。 繼承允許我們根據另一個(gè)類(lèi)來(lái)定義一個(gè)類(lèi),這使得更容易創(chuàng )建和維護應用程序。 這也提供了重用代碼功能和快速實(shí)現時(shí)間的機會(huì )。
在創(chuàng )建類(lèi)時(shí),程序員可以指定新類(lèi)應該繼承現有類(lèi)的成員,而不是編寫(xiě)完全新的數據成員和成員函數。 這個(gè)現有類(lèi)稱(chēng)為基類(lèi),新類(lèi)稱(chēng)為派生類(lèi)。
類(lèi)可以從多個(gè)類(lèi)或接口派生,這意味著(zhù)它可以從多個(gè)基類(lèi)或接口繼承數據和函數。
VB.Net中用于創(chuàng )建派生類(lèi)的語(yǔ)法如下:
- <access-specifier> Class <base_class>
- ...
- End Class
- Class <derived_class>: Inherits <base_class>
- ...
- End Class
考慮一個(gè)基類(lèi)Shape和它的派生類(lèi)Rectangle:
- ' Base class
- Class Shape
- Protected width As Integer
- Protected height As Integer
- Public Sub setWidth(ByVal w As Integer)
- width = w
- End Sub
- Public Sub setHeight(ByVal h As Integer)
- height = h
- End Sub
- End Class
- ' Derived class
- Class Rectangle : Inherits Shape
- Public Function getArea() As Integer
- Return (width * height)
- End Function
- End Class
- Class RectangleTester
- Shared Sub Main()
- Dim rect As Rectangle = New Rectangle()
- rect.setWidth(5)
- rect.setHeight(7)
- ' Print the area of the object.
- Console.WriteLine('Total area: {0}', rect.getArea())
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
Total area: 35派生類(lèi)繼承基類(lèi)成員變量和成員方法。 因此,應該在創(chuàng )建子類(lèi)之前創(chuàng )建超類(lèi)對象。 超類(lèi)或基類(lèi)在VB.Net中被稱(chēng)為MyBase
以下程序演示了這一點(diǎn):
- ' Base class
- Class Rectangle
- Protected width As Double
- Protected length As Double
- Public Sub New(ByVal l As Double, ByVal w As Double)
- length = l
- width = w
- End Sub
- Public Function GetArea() As Double
- Return (width * length)
- End Function
- Public Overridable Sub Display()
- Console.WriteLine('Length: {0}', length)
- Console.WriteLine('Width: {0}', width)
- Console.WriteLine('Area: {0}', GetArea())
- End Sub
- 'end class Rectangle
- End Class
- 'Derived class
- Class Tabletop : Inherits Rectangle
- Private cost As Double
- Public Sub New(ByVal l As Double, ByVal w As Double)
- MyBase.New(l, w)
- End Sub
- Public Function GetCost() As Double
- Dim cost As Double
- cost = GetArea() * 70
- Return cost
- End Function
- Public Overrides Sub Display()
- MyBase.Display()
- Console.WriteLine('Cost: {0}', GetCost())
- End Sub
- 'end class Tabletop
- End Class
- Class RectangleTester
- Shared Sub Main()
- Dim t As Tabletop = New Tabletop(4.5, 7.5)
- t.Display()
- Console.ReadKey()
- End Sub
- End Class
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Length: 4.5
- Width: 7.5
- Area: 33.75
- Cost: 2362.5
VB.Net支持多重繼承。
異常是在程序執行期間出現的問(wèn)題。 例外是對程序運行時(shí)出現的異常情況的響應,例如嘗試除以零。
異常提供了一種將控制從程序的一個(gè)部分轉移到另一個(gè)部分的方法。 VB.Net異常處理建立在四個(gè)關(guān)鍵字:Try,Catch,Finally和Throw。
Try: A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks. Try塊標識將激活特定異常的代碼塊。 它后面是一個(gè)或多個(gè)Catch塊。
Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception. 程序捕獲異常,并在程序中要處理問(wèn)題的位置使用異常處理程序。 Catch關(guān)鍵字表示捕獲異常。
Finally: The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. 最后:Finally塊用于執行給定的一組語(yǔ)句,無(wú)論是拋出還是不拋出異常。 例如,如果打開(kāi)一個(gè)文件,那么無(wú)論是否引發(fā)異常,都必須關(guān)閉該文件。
Throw: A program throws an exception when a problem shows up. This is done using a Throw keyword. 當出現問(wèn)題時(shí),程序拋出異常。 這是使用Throw關(guān)鍵字完成的。
假設塊將引發(fā)異常,則方法使用Try和Catch關(guān)鍵字的組合捕獲異常。 Try / Catch塊放置在可能生成異常的代碼周?chē)?Try / Catch塊中的代碼稱(chēng)為受保護代碼,使用Try / Catch的語(yǔ)法如下所示:
- Try
- [ tryStatements ]
- [ Exit Try ]
- [ Catch [ exception [ As type ] ] [ When expression ]
- [ catchStatements ]
- [ Exit Try ] ]
- [ Catch ... ]
- [ Finally
- [ finallyStatements ] ]
- End Try
您可以列出多個(gè)catch語(yǔ)句以捕獲不同類(lèi)型的異常,以防您的try塊在不同情況下引發(fā)多個(gè)異常。
在.Net框架中,異常由類(lèi)表示。 .Net Framework中的異常類(lèi)主要直接或間接從System.Exception類(lèi)派生。 從System.Exception類(lèi)派生的一些異常類(lèi)是System.ApplicationException和System.SystemException類(lèi)。
System.ApplicationException類(lèi)支持由應用程序生成的異常。 所以程序員定義的異常應該從這個(gè)類(lèi)派生。
System.SystemException類(lèi)是所有預定義系統異常的基類(lèi)。
下表提供了從Sytem.SystemException類(lèi)派生的一些預定義異常類(lèi):
| 異常類(lèi) | 描述 |
|---|---|
| System.IO.IOException | Handles I/O errors. 處理I / O錯誤。 |
| System.IndexOutOfRangeException | Handles errors generated when a method refers to an array index out of range. 當處理的方法是指一個(gè)數組索引超出范圍產(chǎn)生的錯誤。 |
| System.ArrayTypeMismatchException | Handles errors generated when type is mismatched with the array type 處理類(lèi)型與數組類(lèi)型不匹配時(shí)生成的錯誤。. |
| System.NullReferenceException | Handles errors generated from deferencing a null object. 處理從取消引用空對象生成的錯誤。 |
| System.DivideByZeroException | Handles errors generated from dividing a dividend with zero. 處理將股利除以零所產(chǎn)生的錯誤。 |
| System.InvalidCastException | Handles errors generated during typecasting. 處理類(lèi)型轉換期間生成的錯誤。 |
| 為System.OutOfMemoryException | Handles errors generated from insufficient free memory. 處理來(lái)自可用內存不足產(chǎn)生的錯誤。 |
| System.StackOverflowException | Handles errors generated from stack overflow. 處理來(lái)自堆棧溢出產(chǎn)生的錯誤。 |
VB.Net提供了一個(gè)結構化的解決方案,以try和catch塊的形式處理異常處理問(wèn)題。 使用這些塊,核心程序語(yǔ)句與錯誤處理語(yǔ)句分離。
這些錯誤處理塊使用Try,Catch和Finally關(guān)鍵字實(shí)現。 以下是在零除條件時(shí)拋出異常的示例:
- Module exceptionProg
- Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
- Dim result As Integer
- Try
- result = num1 num2
- Catch e As DivideByZeroException
- Console.WriteLine('Exception caught: {0}', e)
- Finally
- Console.WriteLine('Result: {0}', result)
- End Try
- End Sub
- Sub Main()
- division(25, 0)
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- Exception caught: System.DivideByZeroException: Attempted to divide by zero.
- at ...
- Result: 0
您還可以定義自己的異常。 用戶(hù)定義的異常類(lèi)派生自ApplicationException類(lèi)。 以下示例演示了這一點(diǎn):
- Module exceptionProg
- Public Class TempIsZeroException : Inherits ApplicationException
- Public Sub New(ByVal message As String)
- MyBase.New(message)
- End Sub
- End Class
- Public Class Temperature
- Dim temperature As Integer = 0
- Sub showTemp()
- If (temperature = 0) Then
- Throw (New TempIsZeroException('Zero Temperature found'))
- Else
- Console.WriteLine('Temperature: {0}', temperature)
- End If
- End Sub
- End Class
- Sub Main()
- Dim temp As Temperature = New Temperature()
- Try
- temp.showTemp()
- Catch e As TempIsZeroException
- Console.WriteLine('TempIsZeroException: {0}', e.Message)
- End Try
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
TempIsZeroException: Zero Temperature found如果它是直接或間接從System.Exception類(lèi)派生的,你可以?huà)伋鲆粋€(gè)對象。
你可以在catch塊中使用throw語(yǔ)句來(lái)拋出當前對象:
Throw [ expression ]下面的程序說(shuō)明了這一點(diǎn):
- Module exceptionProg
- Sub Main()
- Try
- Throw New ApplicationException('A custom exception _
- is being thrown here...')
- Catch e As Exception
- Console.WriteLine(e.Message)
- Finally
- Console.WriteLine('Now inside the Finally Block')
- End Try
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
- A custom exception is being thrown here...
- Now inside the Finally Block
Afileis是存儲在具有特定名稱(chēng)和目錄路徑的磁盤(pán)中的數據的集合。 當打開(kāi)文件進(jìn)行讀取或寫(xiě)入時(shí),它變?yōu)閍stream。
流基本上是通過(guò)通信路徑的字節序列。 有兩個(gè)主要流:輸入流和輸出流。 輸入流用于從文件讀取數據(讀取操作)和輸出流用于寫(xiě)入文件(寫(xiě)入操作)。
System.IO命名空間具有用于對文件執行各種操作的各種類(lèi),例如創(chuàng )建和刪除文件,讀取或寫(xiě)入文件,關(guān)閉文件等。
下表顯示了System.IO命名空間中一些常用的非抽象類(lèi):
| I / O類(lèi) | 描述 |
|---|---|
| BinaryReader | 讀取二進(jìn)制流的基本數據。 |
| BinaryWriter | 以二進(jìn)制格式寫(xiě)入原始數據。 |
| BufferedStream | 對于字節流的臨時(shí)存儲。 |
| Directory | 有助于操縱的目錄結構。 |
| DirectoryInfo | 用于對目錄進(jìn)行操作。 |
| DriveInfo | 提供了驅動(dòng)器的信息。 |
| File | 有助于處理文件。 |
| FileInfo | 用于對文件執行操作。 |
| FileStream | 用于讀,寫(xiě)在文件中的任何位置。 |
| MemoryStream | 用于存儲在存儲器流傳輸數據的隨機訪(fǎng)問(wèn)。 |
| Path | 在執行路徑信息的操作。 |
| StreamReader | 用于從字節流讀取字符。 |
| StreamWriter | 用于寫(xiě)入字符流。 |
| StringReader | 用于從字符串緩沖區中讀取。 |
| StringWriter | 用于寫(xiě)入字符串緩沖區。 |
System.IO命名空間中的FileStream類(lèi)有助于讀取,寫(xiě)入和關(guān)閉文件。 此類(lèi)派生自抽象類(lèi)Stream。
您需要創(chuàng )建一個(gè)FileStream對象來(lái)創(chuàng )建一個(gè)新文件或打開(kāi)一個(gè)現有文件。 創(chuàng )建一個(gè)FileStream對象的語(yǔ)法如下:
Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)例如,為創(chuàng )建FileStream對象讀取文件namedsample.txt:
Dim f1 As FileStream = New FileStream('sample.txt', FileMode.OpenOrCreate, FileAccess.ReadWrite)| 參數 | 描述 |
|---|---|
| FileMode | FileModeenumerator定義了打開(kāi)文件的各種方法。 FileMode枚舉器的成員是:
|
| FileAccess | FileAccessenumerators有成員:Read,ReadWriteandWrite。 |
| FileShare | FileShareenumerators有以下成員:
|
下面的程序演示使用FileStream類(lèi):
- Imports System.IO
- Module fileProg
- Sub Main()
- Dim f1 As FileStream = New FileStream('sample.txt', _
- FileMode.OpenOrCreate, FileAccess.ReadWrite)
- Dim i As Integer
- For i = 0 To 20
- f1.WriteByte(CByte(i))
- Next i
- f1.Position = 0
- For i = 0 To 20
- Console.Write('{0} ', f1.ReadByte())
- Next i
- f1.Close()
- Console.ReadKey()
- End Sub
- End Module
當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1上面的示例在VB.Net中提供了簡(jiǎn)單的文件操作。 然而,為了利用System.IO類(lèi)的巨大能力,你需要知道這些類(lèi)的常用屬性和方法。
我們將討論這些類(lèi)以及它們在以下部分中執行的操作。 請點(diǎn)擊提供的鏈接以獲取各個(gè)部分:
| 主題和說(shuō)明 |
|---|
| Reading from and Writing into Text files It involves reading from and writing into text files. TheStreamReaderandStreamWriterclasses help to accomplish it. 它涉及從文本文件讀取和寫(xiě)入。 TheStreamReaderandStreamWriterclasses有助于完成它。 |
| Reading from and Writing into Binary files It involves reading from and writing into binary files. TheBinaryReaderandBinaryWriterclasses help to accomplish this. 它涉及從二進(jìn)制文件讀取和寫(xiě)入。 二進(jìn)制Reader和BinaryWriterclasses有助于完成這一任務(wù)。 |
| Manipulating the Windows file system It gives a VB.Net programmer the ability to browse and locate Windows files and directories. 它給了VB.Net程序員瀏覽和定位Windows文件和目錄的能力。 |
對象是通過(guò)使用工具箱控件在Visual Basic窗體上創(chuàng )建的一種用戶(hù)界面元素。 事實(shí)上,在Visual Basic中,表單本身是一個(gè)對象。 每個(gè)Visual Basic控件由三個(gè)重要元素組成:
Properties:描述對象的屬性,
Methods:方法導致對象做某事,
Events:事件是當對象做某事時(shí)發(fā)生的事情。
所有Visual Basic對象可以通過(guò)設置其屬性來(lái)移動(dòng),調整大小或自定義。 屬性是由Visual Basic對象(例如Caption或Fore Color)持有的值或特性。
屬性可以在設計時(shí)通過(guò)使用屬性窗口或在運行時(shí)通過(guò)使用程序代碼中的語(yǔ)句來(lái)設置。
Object. Property = ValueObject is the name of the object you're customizing. Object是您要定制的對象的名稱(chēng)。
Property is the characteristic you want to change. 屬性是您要更改的特性。
Value is the new property setting. Value是新的屬性設置。
例如,
Form1.Caption = 'Hello'您可以使用屬性窗口設置任何窗體屬性。 大多數屬性可以在應用程序執行期間設置或讀取。 您可以參考Microsoft文檔中與應用于它們的不同控件和限制相關(guān)的屬性的完整列表。
方法是作為類(lèi)的成員創(chuàng )建的過(guò)程,它們使對象做某事。 方法用于訪(fǎng)問(wèn)或操縱對象或變量的特性。 您將在類(lèi)中使用的主要有兩類(lèi)方法:
1、如果您使用的工具箱提供的控件之一,您可以調用其任何公共方法。 這種方法的要求取決于所使用的類(lèi)。
2、如果沒(méi)有現有方法可以執行所需的任務(wù),則可以向類(lèi)添加一個(gè)方法。
例如,MessageBox控件有一個(gè)名為Show的方法,它在下面的代碼片段中調用:
- Public Class Form1
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
- Handles Button1.Click
- MessageBox.Show('Hello, World')
- End Sub
- End Class
事件是通知應用程序已發(fā)生重要事件的信號。 例如,當用戶(hù)單擊表單上的控件時(shí),表單可以引發(fā)Click事件并調用處理事件的過(guò)程。 有與窗體相關(guān)聯(lián)的各種類(lèi)型的事件,如點(diǎn)擊,雙擊,關(guān)閉,加載,調整大小等。
以下是表單Load事件處理程序子例程的默認結構。 您可以通過(guò)雙擊代碼來(lái)查看此代碼,這將為您提供與表單控件相關(guān)聯(lián)的所有事件的完整列表:
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- 'event handler code goes here
- End Sub
這里,Handles MyBase.Load表示Form1_Load()子例程處理Load事件。 類(lèi)似的方式,你可以檢查存根代碼點(diǎn)擊,雙擊。 如果你想初始化一些變量,如屬性等,那么你將這樣的代碼保存在Form1_Load()子程序中。 這里,重要的一點(diǎn)是事件處理程序的名稱(chēng),默認情況下是Form1_Load,但您可以根據您在應用程序編程中使用的命名約定更改此名稱(chēng)。
VB.Net提供了各種各樣的控件,幫助您創(chuàng )建豐富的用戶(hù)界面。 所有這些控制的功能在相應的控制類(lèi)中定義。 控制類(lèi)在System.Windows.Forms命名空間中定義。
下表列出了一些常用的控件:
| S.N. | 小部件和說(shuō)明 |
|---|---|
| 1 | Forms 形式 The container for all the controls that make up the user interface. 用于構成用戶(hù)界面的所有控件的容器。 |
| 2 | TextBox 文本框 It represents a Windows text box control. 它代表一個(gè)Windows文本框控件。 |
| 3 | Label 標簽 It represents a standard Windows label. 它代表一個(gè)標準的Windows標簽。 |
| 4 | Button 按鈕 It represents a Windows button control. 它代表一個(gè)Windows按鈕控件。 |
| 5 | ListBox 列表框 It represents a Windows control to display a list of items. 它代表一個(gè)顯示項目列表的Windows控件。 |
| 6 | ComboBox 組合框 It represents a Windows combo box control. 它代表一個(gè)Windows組合框控件。 |
| 7 | RadioButton 單選按鈕 It enables the user to select a single option from a group of choices when paired with other RadioButton controls. 它使用戶(hù)能夠在與其他RadioButton控件配對時(shí)從一組選項中選擇一個(gè)選項。 |
| 8 | CheckBox 復選框 It represents a Windows CheckBox. 它代表一個(gè)Windows復選框。 |
| 9 | PictureBox 圖片框 It represents a Windows picture box control for displaying an image. 它表示用于顯示圖像的Windows畫(huà)面框控件。 |
| 10 | ProgressBar 進(jìn)度條 It represents a Windows progress bar control. 它代表一個(gè)Windows進(jìn)度條控件。 |
| 11 | ScrollBar 滾動(dòng)條 It Implements the basic functionality of a scroll bar control. 它實(shí)現滾動(dòng)條控件的基本功能。 |
| 12 | DateTimePicker 日期輸入框 It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format. 它代表一個(gè)Windows控件,允許用戶(hù)選擇日期和時(shí)間,并以指定的格式顯示日期和時(shí)間。 |
| 13 | TreeView 樹(shù)狀圖 It displays a hierarchical collection of labeled items, each represented by a TreeNode. 它顯示標簽項的分層集合,每個(gè)由樹(shù)節點(diǎn)表示。 |
| 14 | ListView 列表顯示 It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views. 它代表一個(gè)Windows列表視圖控件,它顯示可以使用四個(gè)不同視圖之一顯示的項目集合。 |
有許多內置的對話(huà)框,用于Windows窗體中的各種任務(wù),例如打開(kāi)和保存文件,打印頁(yè)面,向應用程序的用戶(hù)提供顏色,字體,頁(yè)面設置等選擇。 這些內置的對話(huà)框減少了開(kāi)發(fā)人員的時(shí)間和工作量。
所有這些對話(huà)框控件類(lèi)繼承自CommonDialog類(lèi),并覆蓋基類(lèi)的RunDialog()函數以創(chuàng )建特定對話(huà)框。
當對話(huà)框的用戶(hù)調用其ShowDialog()函數時(shí),將自動(dòng)調用RunDialog()函數。
ShowDialog方法用于在運行時(shí)顯示所有對話(huà)框控件。 它返回一個(gè)DialogResult枚舉類(lèi)型的值。 DialogResult枚舉的值為:
Abort 中止 - returns DialogResult.Abort value, when user clicks an Abort button. 當用戶(hù)單擊“中止”按鈕時(shí),返回DialogResult.Abort值。
Cancel 取消 -returns DialogResult.Cancel, when user clicks a Cancel button. 當用戶(hù)單擊Ignore按鈕時(shí),返回DialogResult.Ignore。
Ignore 忽略 -returns DialogResult.Ignore, when user clicks an Ignore button. 返回DialogResult.No,當用戶(hù)單擊否按鈕。
No -returns DialogResult.No, when user clicks a No button. 不返回任何內容,對話(huà)框繼續運行。
None 無(wú) -returns nothing and the dialog box continues running. 返回DialogResult.OK,當用戶(hù)單擊確定按鈕
OK -returns DialogResult.OK, when user clicks an OK button. 返回DialogResult. OK,當用戶(hù)點(diǎn)擊OK鍵
Retry 重試 -returns DialogResult.Retry , when user clicks an Retry button. 當用戶(hù)單擊重試按鈕時(shí),返回DialogResult.Retry
Yes -returns DialogResult.Yes, when user clicks an Yes button. 返回DialogResult.Yes,當用戶(hù)單擊是按鈕
下圖顯示了通用對話(huà)框類(lèi)繼承:

上述的所有類(lèi)都有相應的控件,可以在設計期間從工具箱中添加。 您可以通過(guò)以編程方式實(shí)例化類(lèi)或通過(guò)使用相關(guān)控件,將這些類(lèi)的相關(guān)功能包括到應用程序中。
當雙擊工具箱中的任何對話(huà)框控件或將控件拖動(dòng)到窗體上時(shí),它將顯示在Windows窗體設計器底部的組件托盤(pán)中,但不會(huì )直接顯示在窗體上。
下表列出了常用的對話(huà)框控件。 點(diǎn)擊以下鏈接查看其詳細信息:
| S.N. | 控制& 說(shuō)明 |
|---|---|
| 1 | ColorDialog It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors. 它表示一個(gè)公共對話(huà)框,顯示可用顏色以及允許用戶(hù)定義自定義顏色的控件。 |
| 2 | FontDialog It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color. 它提示用戶(hù)從安裝在本地計算機上的字體中選擇字體,并讓用戶(hù)選擇字體,字體大小和顏色。 |
| 3 | OpenFileDialog It prompts the user to open a file and allows the user to select a file to open. 它提示用戶(hù)打開(kāi)文件,并允許用戶(hù)選擇要打開(kāi)的文件。 |
| 4 | SaveFileDialog It prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. 它提示用戶(hù)選擇保存文件的位置,并允許用戶(hù)指定保存數據的文件的名稱(chēng)。 |
| 5 | PrintDialog It lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application. 它允許用戶(hù)通過(guò)選擇打印機并從Windows窗體應用程序中選擇要打印的文檔的哪些部分來(lái)打印文檔。 |
在本章中,我們將研究以下概念:
在應用程序中添加菜單和子菜單
在表單中添加剪切,復制和粘貼功能
錨定和對接控制在一種形式
模態(tài)形式
傳統上,Menu,MainMenu,ContextMenu和MenuItem類(lèi)用于在Windows應用程序中添加菜單,子菜單和上下文菜單。
現在,MenuStrip,ToolStripMenuItem,ToolStripDropDown和ToolStripDropDownMenu控件替換和添加功能到以前版本的菜單相關(guān)的控件。 但是,舊的控制類(lèi)保留為向后兼容和未來(lái)使用。
讓我們首先使用舊版本控件創(chuàng )建典型的Windows主菜單欄和子菜單,因為這些控件在舊應用程序中仍然很常用。
以下是一個(gè)示例,顯示了如何使用菜單項創(chuàng )建菜單欄:文件,編輯,視圖和項目。 文件菜單有子菜單新建,打開(kāi)和保存。
讓我們雙擊窗體,并在打開(kāi)的窗口中放下面的代碼。
- Public Class Form1
- Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
- 'defining the main menu bar
- Dim mnuBar As New MainMenu()
- 'defining the menu items for the main menu bar
- Dim myMenuItemFile As New MenuItem('&File')
- Dim myMenuItemEdit As New MenuItem('&Edit')
- Dim myMenuItemView As New MenuItem('&View')
- Dim myMenuItemProject As New MenuItem('&Project')
- 'adding the menu items to the main menu bar
- mnuBar.MenuItems.Add(myMenuItemFile)
- mnuBar.MenuItems.Add(myMenuItemEdit)
- mnuBar.MenuItems.Add(myMenuItemView)
- mnuBar.MenuItems.Add(myMenuItemProject)
- ' defining some sub menus
- Dim myMenuItemNew As New MenuItem('&New')
- Dim myMenuItemOpen As New MenuItem('&Open')
- Dim myMenuItemSave As New MenuItem('&Save')
- 'add sub menus to the File menu
- myMenuItemFile.MenuItems.Add(myMenuItemNew)
- myMenuItemFile.MenuItems.Add(myMenuItemOpen)
- myMenuItemFile.MenuItems.Add(myMenuItemSave)
- 'add the main menu to the form
- Me.Menu = mnuBar
- ' Set the caption bar text of the form.
- Me.Text = 'tutorialspoint.com'
- End Sub
- End Class
當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

Windows窗體包含一組豐富的類(lèi),用于創(chuàng )建您自己的具有現代外觀(guān),外觀(guān)和感覺(jué)的自定義菜單。 MenuStrip,ToolStripMenuItem,ContextMenuStrip控件用于有效地創(chuàng )建菜單欄和上下文菜單。
點(diǎn)擊以下鏈接查看他們的詳細信息:
| S.N. | Control & Description |
|---|---|
| 1 | MenuStrip It provides a menu system for a form. 它為表單提供了一個(gè)菜單系統。 |
| 2 | ToolStripMenuItem It represents a selectable option displayed on a MenuStrip orContextMenuStrip. The ToolStripMenuItem control replaces and adds functionality to the MenuItem control of previous versions. 它表示在MenuStrip或ContextMenuStrip上顯示的可選選項。 ToolStripMenuItem控件替換和添加以前版本的MenuItem控件的功能。 |
| 2 | ContextMenuStrip It represents a shortcut menu. 它代表一個(gè)快捷菜單。 |
ClipBoard類(lèi)公開(kāi)的方法用于在應用程序中添加剪切,復制和粘貼功能。 ClipBoard類(lèi)提供了在系統剪貼板上放置數據和檢索數據的方法。
它有以下常用的方法:
| SN | 方法名稱(chēng)和說(shuō)明 |
|---|---|
| 1 | Clear Removes all data from the Clipboard. 刪除從剪貼板中的所有數據。 |
| 2 | ContainsData Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format. 指示是否有上是在指定的格式或可轉換成此格式的剪貼板中的數據。 |
| 3 | ContainsImage Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format. 指示是否有關(guān)于那就是在Bitmap格式或可轉換成該格式剪貼板數據。 |
| 4 | ContainsText Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system. 指示是否在文本或UnicodeText格式剪貼板中的數據,根據不同的操作系統。 |
| 5 | GetData Retrieves data from the Clipboard in the specified format. 從指定格式的剪貼板中檢索數據。 |
| 6 | GetDataObject Retrieves the data that is currently on the system Clipboard. 檢索是目前系統剪貼板中的數據。 |
| 7 | getImage Retrieves an image from the Clipboard. 檢索從剪貼板中的圖像。 |
| 8 | getText Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system. 從文本或UnicodeText格式剪貼板中檢索文本數據,根據不同的操作系統。 |
| 9 | getText(TextDataFormat) Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value. 從由指定TextDataFormat值指示的格式剪貼板中檢索文本數據。 |
| 10 | SetData Clears the Clipboard and then adds data in the specified format. 清除剪貼板,然后以指定的格式將數據添加。 |
| 11 | setText(String) Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system. 清除剪貼板,然后添加在文本或UnicodeText格式的文本數據,根據不同的操作系統。 |
以下是一個(gè)示例,其中顯示了如何使用Clipboard類(lèi)的方法剪切,復制和粘貼數據。 執行以下步驟:
在表單上添加豐富的文本框控件和三個(gè)按鈕控件。
將按鈕的文本屬性分別更改為“剪切”,“復制”和“粘貼”。
雙擊按鈕,在代碼編輯器中添加以下代碼:
- 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 = 'tutorialspoint.com'
- End Sub
- Private Sub Button1_Click(sender As Object, e As EventArgs) _
- Handles Button1.Click
- Clipboard.SetDataObject(RichTextBox1.SelectedText)
- RichTextBox1.SelectedText = ''
- End Sub
- Private Sub Button2_Click(sender As Object, e As EventArgs) _
- Handles Button2.Click
- Clipboard.SetDataObject(RichTextBox1.SelectedText)
- End Sub
- Private Sub Button3_Click(sender As Object, e As EventArgs) _
- Handles Button3.Click
- Dim iData As IDataObject
- iData = Clipboard.GetDataObject()
- If (iData.GetDataPresent(DataFormats.Text)) Then
- RichTextBox1.SelectedText = iData.GetData(DataFormats.Text)
- Else
- RichTextBox1.SelectedText = ' '
- End If
- End Sub
- End Class
當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

輸入一些文本并檢查按鈕的工作方式。
錨定允許您設置控件的定位點(diǎn)位置到其容器的控件,例如,窗體的邊緣??丶?lèi) Anchor 屬性允許您設置此屬性的值。Anchor 屬性獲取或設置一個(gè)控件綁定和確定如何調整控件的大小與它的父容器的邊緣。
當你錨定到窗體控件時(shí),該控件維護它距離邊緣的形式和其錨的位置,當窗體調整。
你可以從屬性窗口設置控件的錨屬性值︰

輸入一些文本并檢查按鈕的工作方式。
例如,讓我們在表單上添加一個(gè)Button控件,并將其anchor屬性設置為Bottom,Right。 運行此窗體以查看Button控件相對于窗體的原始位置。

現在,當拉伸窗體時(shí),Button和窗體右下角之間的距離保持不變。

控制裝置的對接意味著(zhù)將其對接到其容器的邊緣之一。 在對接中,控制完全填充容器的某些區域。
Control類(lèi)的Dock屬性執行此操作。 Dock屬性獲取或設置哪些控件邊界??康狡涓缚丶?,并確定如何使用其父控件調整控件大小。
您可以從“屬性”窗口設置控件的Dock屬性值:

例如,讓我們在表單上添加一個(gè)Button控件,并將其Dock屬性設置為Bottom。 運行此窗體以查看Button控件相對于窗體的原始位置。

現在,當你拉伸窗體時(shí),Button會(huì )調整窗體的大小。

您可以通過(guò)兩種方式調用模式窗體:
調用ShowDialog方法
調用Show方法
讓我們舉一個(gè)例子,我們將創(chuàng )建一個(gè)模態(tài)形式,一個(gè)對話(huà)框。 執行以下步驟:
將表單Form1添加到您的應用程序,并向Form1添加兩個(gè)標簽和一個(gè)按鈕控件
將第一個(gè)標簽和按鈕的文本屬性分別更改為“歡迎使用教程點(diǎn)”和“輸入您的名稱(chēng)”。 將第二個(gè)標簽的文本屬性保留為空。

添加一個(gè)新的Windows窗體,Form2,并向Form2添加兩個(gè)按鈕,一個(gè)標簽和一個(gè)文本框。
將按鈕的文本屬性分別更改為“確定”和“取消”。 將標簽的文本屬性更改為“輸入您的姓名:”。
將Form2的FormBorderStyle屬性設置為FixedDialog,為其提供對話(huà)框邊框。
將Form2的ControlBox屬性設置為False。
將Form2的ShowInTaskbar屬性設置為False。
將OK按鈕的DialogResult屬性設置為OK,將Cancel按鈕設置為Cancel。

在Form2的Form2_Load方法中添加以下代碼片段:
- Private Sub Form2_Load(sender As Object, e As EventArgs) _
- Handles MyBase.Load
- AcceptButton = Button1
- CancelButton = Button2
- End Sub
在Form1的Button1_Click方法中添加以下代碼片段:
- Private Sub Button1_Click(sender As Object, e As EventArgs) _
- Handles Button1.Click
- Dim frmSecond As Form2 = New Form2()
- If frmSecond.ShowDialog() = DialogResult.OK Then
- Label2.Text = frmSecond.TextBox1.Text
- End If
- End Sub
當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

點(diǎn)擊“輸入您的姓名”按鈕顯示第二個(gè)表單:

單擊確定按鈕將控制和信息從模態(tài)形式返回到先前的形式:

事件基本上是一個(gè)用戶(hù)操作,如按鍵,點(diǎn)擊,鼠標移動(dòng)等,或某些事件,如系統生成的通知。 應用程序需要在事件發(fā)生時(shí)對其進(jìn)行響應。
單擊按鈕,或在文本框中輸入某些文本,或單擊菜單項,都是事件的示例。 事件是調用函數或可能導致另一個(gè)事件的操作。
事件處理程序是指示如何響應事件的函數。
VB.Net是一種事件驅動(dòng)的語(yǔ)言。 主要有兩種類(lèi)型的事件:
鼠標事件 Mouse events
鍵盤(pán)事件 Keyboard events
鼠標事件發(fā)生與鼠標移動(dòng)形式和控件。以下是與Control類(lèi)相關(guān)的各種鼠標事件:
MouseDown -當按下鼠標按鈕時(shí)發(fā)生
MouseEnter -當鼠標指針進(jìn)入控件時(shí)發(fā)生
MouseHover -當鼠標指針懸停在控件上時(shí)發(fā)生
MouseLeave -鼠標指針離開(kāi)控件時(shí)發(fā)生
MouseMove -當鼠標指針移動(dòng)到控件上時(shí)
MouseUp -當鼠標指針在控件上方并且鼠標按鈕被釋放時(shí)發(fā)生
MouseWheel -它發(fā)生在鼠標滾輪移動(dòng)和控件有焦點(diǎn)時(shí)
鼠標事件的事件處理程序獲得一個(gè)類(lèi)型為MouseEventArgs的參數。 MouseEventArgs對象用于處理鼠標事件。它具有以下屬性:
Buttons-表示按下鼠標按鈕
Clicks-顯示點(diǎn)擊次數
Delta-表示鼠標輪旋轉的定位槽的數量
X -指示鼠標點(diǎn)擊的x坐標
Y -表示鼠標點(diǎn)擊的y坐標
下面是一個(gè)例子,它展示了如何處理鼠標事件。執行以下步驟:
在表單中添加三個(gè)標簽,三個(gè)文本框和一個(gè)按鈕控件。
將標簽的文本屬性分別更改為 - 客戶(hù)ID,名稱(chēng)和地址。
將文本框的名稱(chēng)屬性分別更改為txtID,txtName和txtAddress。
將按鈕的文本屬性更改為“提交”。
在代碼編輯器窗口中添加以下代碼:
- 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工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

嘗試在文本框中輸入文字,并檢查鼠標事件:

以下是與Control類(lèi)相關(guān)的各種鍵盤(pán)事件:
KeyDown -當按下一個(gè)鍵并且控件具有焦點(diǎn)時(shí)發(fā)生
KeyPress -當按下一個(gè)鍵并且控件具有焦點(diǎn)時(shí)發(fā)生
KeyUp -當控件具有焦點(diǎn)時(shí)釋放鍵時(shí)發(fā)生
KeyDown和KeyUp事件的事件處理程序獲得一個(gè)類(lèi)型為KeyEventArgs的參數。此對象具有以下屬性:
Alt -它指示是否按下ALT鍵/ p>
Control-它指示是否按下CTRL鍵
Handled-它指示事件是否被處理
KeyCode- 存儲事件的鍵盤(pán)代碼
KeyData-存儲事件的鍵盤(pán)數據
KeyValue -存儲事件的鍵盤(pán)值
Modifiers-指示按下哪個(gè)修飾鍵(Ctrl,Shift和/或Alt)
Shift-表示是否按下Shift鍵
KeyDown和KeyUp事件的事件處理程序獲得一個(gè)類(lèi)型為KeyEventArgs的參數。此對象具有以下屬性:
Handled-指示KeyPress事件處理
KeyChar -存儲對應于按下的鍵的字符
讓我們繼續前面的例子來(lái)說(shuō)明如何處理鍵盤(pán)事件。 代碼將驗證用戶(hù)為其客戶(hù)ID和年齡輸入一些數字。
添加一個(gè)帶有文本屬性為“Age”的標簽,并添加一個(gè)名為txtAge的相應文本框。
添加以下代碼以處理文本框txtID的KeyUP事件。
添加以下代碼以處理文本框txtID的KeyUP事件。
當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

如果將age或ID的文本留空,或輸入一些非數字數據,則會(huì )出現一個(gè)警告消息框,并清除相應的文本:

未完待續,下一章節,つづく
聯(lián)系客服