欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
VB.NET教程

VB.Net - 類(lèi)與對象

定義類(lèi)時(shí),可以為數據類(lèi)型定義藍圖。 這實(shí)際上并不定義任何數據,但它定義了類(lèi)名的含義,即類(lèi)的對象將包含什么以及可以對這樣的對象執行什么操作。

對象是類(lèi)的實(shí)例。 構成類(lèi)的方法和變量稱(chēng)為類(lèi)的成員。

 

類(lèi)的定義

類(lèi)的定義以關(guān)鍵字Class開(kāi)頭,后跟類(lèi)名稱(chēng); 和類(lèi)體,由End Class語(yǔ)句結束。 以下是類(lèi)定義的一般形式:

  1. [ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
  2. Class name [ ( Of typelist ) ]
  3. [ Inherits classname ]
  4. [ Implements interfacenames ]
  5. [ statements ]
  6. 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)度,寬度和高度:

  1. Module mybox
  2. Class Box
  3. Public length As Double ' Length of a box
  4. Public breadth As Double ' Breadth of a box
  5. Public height As Double ' Height of a box
  6. End Class
  7. Sub Main()
  8. Dim Box1 As Box = New Box() ' Declare Box1 of type Box
  9. Dim Box2 As Box = New Box() ' Declare Box2 of type Box
  10. Dim volume As Double = 0.0 ' Store the volume of a box here
  11. ' box 1 specification
  12. Box1.height = 5.0
  13. Box1.length = 6.0
  14. Box1.breadth = 7.0
  15. ' box 2 specification
  16. Box2.height = 10.0
  17. Box2.length = 12.0
  18. Box2.breadth = 13.0
  19. 'volume of box 1
  20. volume = Box1.height * Box1.length * Box1.breadth
  21. Console.WriteLine('Volume of Box1 : {0}', volume)
  22. 'volume of box 2
  23. volume = Box2.height * Box2.length * Box2.breadth
  24. Console.WriteLine('Volume of Box2 : {0}', volume)
  25. Console.ReadKey()
  26. End Sub
  27. End Module

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Volume of Box1 : 210
  2. 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)成員的值:

  1. Module mybox
  2. Class Box
  3. Public length As Double ' Length of a box
  4. Public breadth As Double ' Breadth of a box
  5. Public height As Double ' Height of a box
  6. Public Sub setLength(ByVal len As Double)
  7. length = len
  8. End Sub
  9. Public Sub setBreadth(ByVal bre As Double)
  10. breadth = bre
  11. End Sub
  12. Public Sub setHeight(ByVal hei As Double)
  13. height = hei
  14. End Sub
  15. Public Function getVolume() As Double
  16. Return length * breadth * height
  17. End Function
  18. End Class
  19. Sub Main()
  20. Dim Box1 As Box = New Box() ' Declare Box1 of type Box
  21. Dim Box2 As Box = New Box() ' Declare Box2 of type Box
  22. Dim volume As Double = 0.0 ' Store the volume of a box here
  23. ' box 1 specification
  24. Box1.setLength(6.0)
  25. Box1.setBreadth(7.0)
  26. Box1.setHeight(5.0)
  27. 'box 2 specification
  28. Box2.setLength(12.0)
  29. Box2.setBreadth(13.0)
  30. Box2.setHeight(10.0)
  31. ' volume of box 1
  32. volume = Box1.getVolume()
  33. Console.WriteLine('Volume of Box1 : {0}', volume)
  34. 'volume of box 2
  35. volume = Box2.getVolume()
  36. Console.WriteLine('Volume of Box2 : {0}', volume)
  37. Console.ReadKey()
  38. End Sub
  39. End Module

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Volume of Box1 : 210
  2. Volume of Box2 : 1560

 

構造函數和析構函數

類(lèi)構造函數是每當我們創(chuàng )建該類(lèi)的新對象時(shí)執行的類(lèi)的特殊成員子類(lèi)。 構造函數具有名稱(chēng)New,并且沒(méi)有任何返回類(lèi)型。

下面的程序解釋了構造函數的概念:

  1. Class Line
  2. Private length As Double ' Length of a line
  3. Public Sub New() 'constructor
  4. Console.WriteLine('Object is being created')
  5. End Sub
  6. Public Sub setLength(ByVal len As Double)
  7. length = len
  8. End Sub
  9. Public Function getLength() As Double
  10. Return length
  11. End Function
  12. Shared Sub Main()
  13. Dim line As Line = New Line()
  14. 'set line length
  15. line.setLength(6.0)
  16. Console.WriteLine('Length of line : {0}', line.getLength())
  17. Console.ReadKey()
  18. End Sub
  19. End Class

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Object is being created
  2. Length of line : 6

默認構造函數沒(méi)有任何參數,但如果需要,構造函數可以有參數。 這樣的構造函數稱(chēng)為參數化構造函數。 此技術(shù)可幫助您在創(chuàng )建對象時(shí)為其分配初始值,如以下示例所示:

  1. Class Line
  2. Private length As Double ' Length of a line
  3. Public Sub New(ByVal len As Double) 'parameterised constructor
  4. Console.WriteLine('Object is being created, length = {0}', len)
  5. length = len
  6. End Sub
  7. Public Sub setLength(ByVal len As Double)
  8. length = len
  9. End Sub
  10. Public Function getLength() As Double
  11. Return length
  12. End Function
  13. Shared Sub Main()
  14. Dim line As Line = New Line(10.0)
  15. Console.WriteLine('Length of line set by constructor : {0}', line.getLength())
  16. 'set line length
  17. line.setLength(6.0)
  18. Console.WriteLine('Length of line set by setLength : {0}', line.getLength())
  19. Console.ReadKey()
  20. End Sub
  21. End Class

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Object is being created, length = 10
  2. Length of line set by constructor : 10
  3. Length of line set by setLength : 6

析構函數是一個(gè)類(lèi)的特殊成員Sub,只要它的類(lèi)的對象超出范圍,它就被執行。


析構函數名為Finalize,它既不能返回值也不能接受任何參數。 析構函數在釋放程序之前釋放資源非常有用,比如關(guān)閉文件,釋放內存等。

析構函數不能繼承或重載。

下面的例子解釋析構函數的概念:

  1. Class Line
  2. Private length As Double ' Length of a line
  3. Public Sub New() 'parameterised constructor
  4. Console.WriteLine('Object is being created')
  5. End Sub
  6. Protected Overrides Sub Finalize() ' destructor
  7. Console.WriteLine('Object is being deleted')
  8. End Sub
  9. Public Sub setLength(ByVal len As Double)
  10. length = len
  11. End Sub
  12. Public Function getLength() As Double
  13. Return length
  14. End Function
  15. Shared Sub Main()
  16. Dim line As Line = New Line()
  17. 'set line length
  18. line.setLength(6.0)
  19. Console.WriteLine('Length of line : {0}', line.getLength())
  20. Console.ReadKey()
  21. End Sub
  22. End Class

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Object is being created
  2. Length of line : 6
  3. Object is being deleted

 

VB.Net類(lèi)的共享成員

我們可以使用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 )建對象之前就存在。

以下示例演示了共享成員的使用:

  1. Class StaticVar
  2. Public Shared num As Integer
  3. Public Sub count()
  4. num = num + 1
  5. End Sub
  6. Public Shared Function getNum() As Integer
  7. Return num
  8. End Function
  9. Shared Sub Main()
  10. Dim s As StaticVar = New StaticVar()
  11. s.count()
  12. s.count()
  13. s.count()
  14. Console.WriteLine('Value of variable num: {0}', StaticVar.getNum())
  15. Console.ReadKey()
  16. End Sub
  17. 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)和派生類(lèi):

類(lèi)可以從多個(gè)類(lèi)或接口派生,這意味著(zhù)它可以從多個(gè)基類(lèi)或接口繼承數據和函數。

VB.Net中用于創(chuàng )建派生類(lèi)的語(yǔ)法如下:

  1. <access-specifier> Class <base_class>
  2. ...
  3. End Class
  4. Class <derived_class>: Inherits <base_class>
  5. ...
  6. End Class

考慮一個(gè)基類(lèi)Shape和它的派生類(lèi)Rectangle:

  1. ' Base class
  2. Class Shape
  3. Protected width As Integer
  4. Protected height As Integer
  5. Public Sub setWidth(ByVal w As Integer)
  6. width = w
  7. End Sub
  8. Public Sub setHeight(ByVal h As Integer)
  9. height = h
  10. End Sub
  11. End Class
  12. ' Derived class
  13. Class Rectangle : Inherits Shape
  14. Public Function getArea() As Integer
  15. Return (width * height)
  16. End Function
  17. End Class
  18. Class RectangleTester
  19. Shared Sub Main()
  20. Dim rect As Rectangle = New Rectangle()
  21. rect.setWidth(5)
  22. rect.setHeight(7)
  23. ' Print the area of the object.
  24. Console.WriteLine('Total area: {0}', rect.getArea())
  25. Console.ReadKey()
  26. End Sub
  27. End Class

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

Total area: 35

 

基類(lèi)初始化

派生類(lèi)繼承基類(lèi)成員變量和成員方法。 因此,應該在創(chuàng )建子類(lèi)之前創(chuàng )建超類(lèi)對象。 超類(lèi)或基類(lèi)在VB.Net中被稱(chēng)為MyBase

以下程序演示了這一點(diǎn):

  1. ' Base class
  2. Class Rectangle
  3. Protected width As Double
  4. Protected length As Double
  5. Public Sub New(ByVal l As Double, ByVal w As Double)
  6. length = l
  7. width = w
  8. End Sub
  9. Public Function GetArea() As Double
  10. Return (width * length)
  11. End Function
  12. Public Overridable Sub Display()
  13. Console.WriteLine('Length: {0}', length)
  14. Console.WriteLine('Width: {0}', width)
  15. Console.WriteLine('Area: {0}', GetArea())
  16. End Sub
  17. 'end class Rectangle
  18. End Class
  19. 'Derived class
  20. Class Tabletop : Inherits Rectangle
  21. Private cost As Double
  22. Public Sub New(ByVal l As Double, ByVal w As Double)
  23. MyBase.New(l, w)
  24. End Sub
  25. Public Function GetCost() As Double
  26. Dim cost As Double
  27. cost = GetArea() * 70
  28. Return cost
  29. End Function
  30. Public Overrides Sub Display()
  31. MyBase.Display()
  32. Console.WriteLine('Cost: {0}', GetCost())
  33. End Sub
  34. 'end class Tabletop
  35. End Class
  36. Class RectangleTester
  37. Shared Sub Main()
  38. Dim t As Tabletop = New Tabletop(4.5, 7.5)
  39. t.Display()
  40. Console.ReadKey()
  41. End Sub
  42. End Class

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Length: 4.5
  2. Width: 7.5
  3. Area: 33.75
  4. Cost: 2362.5

VB.Net支持多重繼承。

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)鍵字完成的。

語(yǔ)法

假設塊將引發(fā)異常,則方法使用Try和Catch關(guān)鍵字的組合捕獲異常。 Try / Catch塊放置在可能生成異常的代碼周?chē)?Try / Catch塊中的代碼稱(chēng)為受保護代碼,使用Try / Catch的語(yǔ)法如下所示:

  1. Try
  2. [ tryStatements ]
  3. [ Exit Try ]
  4. [ Catch [ exception [ As type ] ] [ When expression ]
  5. [ catchStatements ]
  6. [ Exit Try ] ]
  7. [ Catch ... ]
  8. [ Finally
  9. [ finallyStatements ] ]
  10. End Try

您可以列出多個(gè)catch語(yǔ)句以捕獲不同類(lèi)型的異常,以防您的try塊在不同情況下引發(fā)多個(gè)異常。

 

.Net框架中的異常類(lèi)

在.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í)拋出異常的示例:

  1. Module exceptionProg
  2. Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
  3. Dim result As Integer
  4. Try
  5. result = num1 num2
  6. Catch e As DivideByZeroException
  7. Console.WriteLine('Exception caught: {0}', e)
  8. Finally
  9. Console.WriteLine('Result: {0}', result)
  10. End Try
  11. End Sub
  12. Sub Main()
  13. division(25, 0)
  14. Console.ReadKey()
  15. End Sub
  16. End Module

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. Exception caught: System.DivideByZeroException: Attempted to divide by zero.
  2. at ...
  3. Result: 0

 

創(chuàng )建用戶(hù)定義的異常

您還可以定義自己的異常。 用戶(hù)定義的異常類(lèi)派生自ApplicationException類(lèi)。 以下示例演示了這一點(diǎn):

  1. Module exceptionProg
  2. Public Class TempIsZeroException : Inherits ApplicationException
  3. Public Sub New(ByVal message As String)
  4. MyBase.New(message)
  5. End Sub
  6. End Class
  7. Public Class Temperature
  8. Dim temperature As Integer = 0
  9. Sub showTemp()
  10. If (temperature = 0) Then
  11. Throw (New TempIsZeroException('Zero Temperature found'))
  12. Else
  13. Console.WriteLine('Temperature: {0}', temperature)
  14. End If
  15. End Sub
  16. End Class
  17. Sub Main()
  18. Dim temp As Temperature = New Temperature()
  19. Try
  20. temp.showTemp()
  21. Catch e As TempIsZeroException
  22. Console.WriteLine('TempIsZeroException: {0}', e.Message)
  23. End Try
  24. Console.ReadKey()
  25. End Sub
  26. 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):

  1. Module exceptionProg
  2. Sub Main()
  3. Try
  4. Throw New ApplicationException('A custom exception _
  5. is being thrown here...')
  6. Catch e As Exception
  7. Console.WriteLine(e.Message)
  8. Finally
  9. Console.WriteLine('Now inside the Finally Block')
  10. End Try
  11. Console.ReadKey()
  12. End Sub
  13. End Module

當上述代碼被編譯和執行時(shí),它產(chǎn)生了以下結果:

  1. A custom exception is being thrown here...
  2. Now inside the Finally Block

VB.Net - 文件處理

Afileis是存儲在具有特定名稱(chēng)和目錄路徑的磁盤(pán)中的數據的集合。 當打開(kāi)文件進(jìn)行讀取或寫(xiě)入時(shí),它變?yōu)閍stream。

流基本上是通過(guò)通信路徑的字節序列。 有兩個(gè)主要流:輸入流和輸出流。 輸入流用于從文件讀取數據(讀取操作)和輸出流用于寫(xiě)入文件(寫(xiě)入操作)。

 

VB.Net I / O類(lèi)

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ě)入字符串緩沖區。

 

FileStream類(lèi)

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枚舉器的成員是:

  • Append:它打開(kāi)一個(gè)現有文件,并將光標放在文件的末尾,或創(chuàng )建文件,如果該文件不存在。

  • Create:創(chuàng )建一個(gè)新的文件。

  • CreateNew:它指定操作系統應該創(chuàng )建一個(gè)新文件。

  • Open:它打開(kāi)一個(gè)現有文件。

  • OpenOrCreate:它指定操作系統它應該打開(kāi)一個(gè)文件,如果它存在,否則應該創(chuàng )建一個(gè)新文件。

  • Truncate:它打開(kāi)一個(gè)現有文件,并將其大小截斷為零字節。

FileAccess

FileAccessenumerators有成員:Read,ReadWriteandWrite。

FileShare

FileShareenumerators有以下成員:

  • Inheritable:它允許一個(gè)文件句柄傳遞繼承子進(jìn)程

  • None:它拒絕當前文件的共享

  • Read:它可以打開(kāi)文件進(jìn)行讀取

  • ReadWrite:它允許打開(kāi)文件進(jìn)行讀取和寫(xiě)入

  • Write:它允許打開(kāi)寫(xiě)入文件

 

示例:

下面的程序演示使用FileStream類(lèi):

  1. Imports System.IO
  2. Module fileProg
  3. Sub Main()
  4. Dim f1 As FileStream = New FileStream('sample.txt', _
  5. FileMode.OpenOrCreate, FileAccess.ReadWrite)
  6. Dim i As Integer
  7. For i = 0 To 20
  8. f1.WriteByte(CByte(i))
  9. Next i
  10. f1.Position = 0
  11. For i = 0 To 20
  12. Console.Write('{0} ', f1.ReadByte())
  13. Next i
  14. f1.Close()
  15. Console.ReadKey()
  16. End Sub
  17. 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中的高級文件操作

上面的示例在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文件和目錄的能力。

VB.Net - 基本控制

對象是通過(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 = Value
  • Object 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的方法,它在下面的代碼片段中調用:

  1. Public Class Form1
  2. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
  3. Handles Button1.Click
  4. MessageBox.Show('Hello, World')
  5. End Sub
  6. 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)的所有事件的完整列表:

  1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  2. 'event handler code goes here
  3. 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è)不同視圖之一顯示的項目集合。

VB.Net - 對話(huà)框

有許多內置的對話(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)打印文檔。

VB.Net - 高級表單

在本章中,我們將研究以下概念:

  • 在應用程序中添加菜單和子菜單

  • 在表單中添加剪切,復制和粘貼功能

  • 錨定和對接控制在一種形式

  • 模態(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)的窗口中放下面的代碼。

  1. Public Class Form1
  2. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  3. 'defining the main menu bar
  4. Dim mnuBar As New MainMenu()
  5. 'defining the menu items for the main menu bar
  6. Dim myMenuItemFile As New MenuItem('&File')
  7. Dim myMenuItemEdit As New MenuItem('&Edit')
  8. Dim myMenuItemView As New MenuItem('&View')
  9. Dim myMenuItemProject As New MenuItem('&Project')
  10. 'adding the menu items to the main menu bar
  11. mnuBar.MenuItems.Add(myMenuItemFile)
  12. mnuBar.MenuItems.Add(myMenuItemEdit)
  13. mnuBar.MenuItems.Add(myMenuItemView)
  14. mnuBar.MenuItems.Add(myMenuItemProject)
  15. ' defining some sub menus
  16. Dim myMenuItemNew As New MenuItem('&New')
  17. Dim myMenuItemOpen As New MenuItem('&Open')
  18. Dim myMenuItemSave As New MenuItem('&Save')
  19. 'add sub menus to the File menu
  20. myMenuItemFile.MenuItems.Add(myMenuItemNew)
  21. myMenuItemFile.MenuItems.Add(myMenuItemOpen)
  22. myMenuItemFile.MenuItems.Add(myMenuItemSave)
  23. 'add the main menu to the form
  24. Me.Menu = mnuBar
  25. ' Set the caption bar text of the form.
  26. Me.Text = 'tutorialspoint.com'
  27. End Sub
  28. 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è)按鈕控件。

  • 將按鈕的文本屬性分別更改為“剪切”,“復制”和“粘貼”。

  • 雙擊按鈕,在代碼編輯器中添加以下代碼:

  1. Public Class Form1
  2. Private Sub Form1_Load(sender As Object, e As EventArgs) _
  3. Handles MyBase.Load
  4. ' Set the caption bar text of the form.
  5. Me.Text = 'tutorialspoint.com'
  6. End Sub
  7. Private Sub Button1_Click(sender As Object, e As EventArgs) _
  8. Handles Button1.Click
  9. Clipboard.SetDataObject(RichTextBox1.SelectedText)
  10. RichTextBox1.SelectedText = ''
  11. End Sub
  12. Private Sub Button2_Click(sender As Object, e As EventArgs) _
  13. Handles Button2.Click
  14. Clipboard.SetDataObject(RichTextBox1.SelectedText)
  15. End Sub
  16. Private Sub Button3_Click(sender As Object, e As EventArgs) _
  17. Handles Button3.Click
  18. Dim iData As IDataObject
  19. iData = Clipboard.GetDataObject()
  20. If (iData.GetDataPresent(DataFormats.Text)) Then
  21. RichTextBox1.SelectedText = iData.GetData(DataFormats.Text)
  22. Else
  23. RichTextBox1.SelectedText = ' '
  24. End If
  25. End Sub
  26. End Class

當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

輸入一些文本并檢查按鈕的工作方式。

錨定和??吭诖绑w中的控件

錨定允許您設置控件的定位點(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ān)閉或隱藏的窗體,然后才能繼續使用其余應用程序。 所有對話(huà)框都是模態(tài)窗體。 MessageBox也是一種模態(tài)形式。

您可以通過(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方法中添加以下代碼片段:

  1. Private Sub Form2_Load(sender As Object, e As EventArgs) _
  2. Handles MyBase.Load
  3. AcceptButton = Button1
  4. CancelButton = Button2
  5. End Sub

在Form1的Button1_Click方法中添加以下代碼片段:

  1. Private Sub Button1_Click(sender As Object, e As EventArgs) _
  2. Handles Button1.Click
  3. Dim frmSecond As Form2 = New Form2()
  4. If frmSecond.ShowDialog() = DialogResult.OK Then
  5. Label2.Text = frmSecond.TextBox1.Text
  6. End If
  7. End Sub

當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

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

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


VB.Net - 事件處理

事件基本上是一個(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。

  • 將按鈕的文本屬性更改為“提交”。

  • 在代碼編輯器窗口中添加以下代碼:

  1. Public Class Form1
  2. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  3. ' Set the caption bar text of the form.
  4. Me.Text = 'tutorialspont.com'
  5. End Sub
  6. Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_
  7. Handles txtID.MouseEnter
  8. 'code for handling mouse enter on ID textbox
  9. txtID.BackColor = Color.CornflowerBlue
  10. txtID.ForeColor = Color.White
  11. End Sub
  12. Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _
  13. Handles txtID.MouseLeave
  14. 'code for handling mouse leave on ID textbox
  15. txtID.BackColor = Color.White
  16. txtID.ForeColor = Color.Blue
  17. End Sub
  18. Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _
  19. Handles txtName.MouseEnter
  20. 'code for handling mouse enter on Name textbox
  21. txtName.BackColor = Color.CornflowerBlue
  22. txtName.ForeColor = Color.White
  23. End Sub
  24. Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _
  25. Handles txtName.MouseLeave
  26. 'code for handling mouse leave on Name textbox
  27. txtName.BackColor = Color.White
  28. txtName.ForeColor = Color.Blue
  29. End Sub
  30. Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _
  31. Handles txtAddress.MouseEnter
  32. 'code for handling mouse enter on Address textbox
  33. txtAddress.BackColor = Color.CornflowerBlue
  34. txtAddress.ForeColor = Color.White
  35. End Sub
  36. Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _
  37. Handles txtAddress.MouseLeave
  38. 'code for handling mouse leave on Address textbox
  39. txtAddress.BackColor = Color.White
  40. txtAddress.ForeColor = Color.Blue
  41. End Sub
  42. Private Sub Button1_Click(sender As Object, e As EventArgs) _
  43. Handles Button1.Click
  44. MsgBox('Thank you ' & txtName.Text & ', for your kind cooperation')
  45. End Sub
  46. End Class

當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

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

 

處理鍵盤(pán)事件

以下是與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事件。

    1. Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
    2. Handles txtID.KeyUp
    3. If (Not Char.IsNumber(ChrW(e.KeyCode))) Then
    4. MessageBox.Show('Enter numbers for your Customer ID')
    5. txtID.Text = ' '
    6. End If
    7. End Sub
  • 添加以下代碼以處理文本框txtID的KeyUP事件。

    1. Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
    2. Handles txtAge.KeyUp
    3. If (Not Char.IsNumber(ChrW(e.keyCode))) Then
    4. MessageBox.Show('Enter numbers for age')
    5. txtAge.Text = ' '
    6. End If
    7. End Sub

當使用Microsoft Visual Studio工具欄上的“開(kāi)始”按鈕執行并運行上述代碼時(shí),將顯示以下窗口:

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


未完待續,下一章節,つづく

本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
VB.NET New關(guān)鍵字相關(guān)作用剖析
VB愛(ài)好者樂(lè )園(VBGood) - 經(jīng)驗之談 - VB編程的必備技巧
[VB.NET][C#.NET]WindowsForm/控件事件的先后順序/事件方法覆寫(xiě)|愛(ài)工作愛(ài)生活
在VB中使用IE的WebBrowser控件
VB.net學(xué)習筆記(二十六)線(xiàn)程的坎坷人生
自定義VB系統控件
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久