打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
VB.NET教程

VB.Net - 类与对象

定义类时,可以为数据类型定义蓝图。 这实际上并不定义任何数据,但它定义了类名的含义,即类的对象将包含什么以及可以对这样的对象执行什么操作。

对象是类的实例。 构成类的方法和变量称为类的成员。

 

类的定义

类的定义以关键字Class开头,后跟类名称; 和类体,由End Class语句结束。 以下是类定义的一般形式:

  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是一个适用于类的属性列表。 可选的。

  • accessmodifier 访问修改器:defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.  accessmodifier定义类的访问级别,它的值为 - 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.  阴影表示变量在基类中重新声明和隐藏一个同名的元素或一组重载的元素。 可选的。

  • 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指定该类只能用作基类,并且不能直接从它创建对象,即抽象类。 可选的。

  • NotInheritable 不可继承:specifies that the class cannot be used as a base class.  NotInheritable指定该类不能用作基类。

  • Partial 部分:indicates a partial definition of the class.   Partial表示类的部分定义。

  • Inherits 继承:specifies the base class it is inheriting from.  Inherits指定它继承的基类。

  • Implements 实现:specifies the interfaces the class is inheriting from.  Implements指定类继承的接口。

下面的示例演示了一个Box类,它有三个数据成员,长度,宽度和高度:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

 

成员函数和封装

类的成员函数是一个函数,它的定义或其原型在类定义中像任何其他变量一样。 它对它所属的类的任何对象进行操作,并且可以访问该对象的类的所有成员。

成员变量是对象的属性(从设计角度),它们被保持为私有以实现封装。 这些变量只能使用public成员函数访问。

让我们把上面的概念设置并获得类中不同类成员的值:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

 

构造函数和析构函数

类构造函数是每当我们创建该类的新对象时执行的类的特殊成员子类。 构造函数具有名称New,并且没有任何返回类型。

下面的程序解释了构造函数的概念:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

默认构造函数没有任何参数,但如果需要,构造函数可以有参数。 这样的构造函数称为参数化构造函数。 此技术可帮助您在创建对象时为其分配初始值,如以下示例所示:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

析构函数是一个类的特殊成员Sub,只要它的类的对象超出范围,它就被执行。


析构函数名为Finalize,它既不能返回值也不能接受任何参数。 析构函数在释放程序之前释放资源非常有用,比如关闭文件,释放内存等。

析构函数不能继承或重载。

下面的例子解释析构函数的概念:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

 

VB.Net类的共享成员

我们可以使用Shared关键字将类成员定义为静态。 当我们将一个类的成员声明为Shared时,意味着无论创建多少个对象,该成员只有一个副本。

关键字“共享”意味着类只存在一个成员实例。 共享变量用于定义常量,因为它们的值可以通过调用类而不创建它的实例来检索。

共享变量可以在成员函数或类定义之外初始化。 您还可以在类定义中初始化共享变量。

您还可以将成员函数声明为共享。 这样的函数只能访问共享变量。 共享函数甚至在创建对象之前就存在。

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

  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

当上述代码被编译和执行时,它产生了以下结果:

Value of variable num: 3

 

继承

面向对象编程中最重要的概念之一是继承。 继承允许我们根据另一个类来定义一个类,这使得更容易创建和维护应用程序。 这也提供了重用代码功能和快速实现时间的机会。

在创建类时,程序员可以指定新类应该继承现有类的成员,而不是编写完全新的数据成员和成员函数。 这个现有类称为基类,新类称为派生类。

 

基类和派生类:

类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。

VB.Net中用于创建派生类的语法如下:

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

考虑一个基类Shape和它的派生类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

当上述代码被编译和执行时,它产生了以下结果:

Total area: 35

 

基类初始化

派生类继承基类成员变量和成员方法。 因此,应该在创建子类之前创建超类对象。 超类或基类在VB.Net中被称为MyBase

以下程序演示了这一点:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

VB.Net支持多重继承。

VB.Net - 异常处理

异常是在程序执行期间出现的问题。 例外是对程序运行时出现的异常情况的响应,例如尝试除以零。
 

异常提供了一种将控制从程序的一个部分转移到另一个部分的方法。 VB.Net异常处理建立在四个关键字: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块标识将激活特定异常的代码块。 它后面是一个或多个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.  程序捕获异常,并在程序中要处理问题的位置使用异常处理程序。 Catch关键字表示捕获异常。

  • 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块用于执行给定的一组语句,无论是抛出还是不抛出异常。 例如,如果打开一个文件,那么无论是否引发异常,都必须关闭该文件。

  • Throw: A program throws an exception when a problem shows up. This is done using a Throw keyword.  当出现问题时,程序抛出异常。 这是使用Throw关键字完成的。

语法

假设块将引发异常,则方法使用Try和Catch关键字的组合捕获异常。 Try / Catch块放置在可能生成异常的代码周围。 Try / Catch块中的代码称为受保护代码,使用Try / Catch的语法如下所示:

  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

您可以列出多个catch语句以捕获不同类型的异常,以防您的try块在不同情况下引发多个异常。

 

.Net框架中的异常类

在.Net框架中,异常由类表示。 .Net Framework中的异常类主要直接或间接从System.Exception类派生。 从System.Exception类派生的一些异常类是System.ApplicationException和System.SystemException类。

System.ApplicationException类支持由应用程序生成的异常。 所以程序员定义的异常应该从这个类派生。

System.SystemException类是所有预定义系统异常的基类。

下表提供了从Sytem.SystemException类派生的一些预定义异常类:

异常类 描述
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.
当处理的方法是指一个数组索引超出范围产生的错误。
System.ArrayTypeMismatchException

Handles errors generated when type is mismatched with the array type

处理类型与数组类型不匹配时生成的错误。.

System.NullReferenceException Handles errors generated from deferencing a null object.
处理从取消引用空对象生成的错误。
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
处理将股利除以零所产生的错误。
System.InvalidCastException Handles errors generated during typecasting.
处理类型转换期间生成的错误。
为System.OutOfMemoryException Handles errors generated from insufficient free memory.
处理来自可用内存不足产生的错误。
System.StackOverflowException Handles errors generated from stack overflow.
处理来自堆栈溢出产生的错误。

 

处理异常

VB.Net提供了一个结构化的解决方案,以try和catch块的形式处理异常处理问题。 使用这些块,核心程序语句与错误处理语句分离。

这些错误处理块使用Try,Catch和Finally关键字实现。 以下是在零除条件时抛出异常的示例:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

 

创建用户定义的异常

您还可以定义自己的异常。 用户定义的异常类派生自ApplicationException类。 以下示例演示了这一点:

  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

当上述代码被编译和执行时,它产生了以下结果:

TempIsZeroException: Zero Temperature found

 

掷物投掷对象

 

如果它是直接或间接从System.Exception类派生的,你可以抛出一个对象。

你可以在catch块中使用throw语句来抛出当前对象:

Throw [ expression ]

下面的程序说明了这一点:

  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

当上述代码被编译和执行时,它产生了以下结果:

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

VB.Net - 文件处理

Afileis是存储在具有特定名称和目录路径的磁盘中的数据的集合。 当打开文件进行读取或写入时,它变为astream。

流基本上是通过通信路径的字节序列。 有两个主要流:输入流和输出流。 输入流用于从文件读取数据(读取操作)和输出流用于写入文件(写入操作)。

 

VB.Net I / O类

System.IO命名空间具有用于对文件执行各种操作的各种类,例如创建和删除文件,读取或写入文件,关闭文件等。

下表显示了System.IO命名空间中一些常用的非抽象类:

I / O类 描述
BinaryReader 读取二进制流的基本数据。
BinaryWriter 以二进制格式写入原始数据。
BufferedStream 对于字节流的临时存储。
Directory 有助于操纵的目录结构。
DirectoryInfo 用于对目录进行操作。
DriveInfo 提供了驱动器的信息。
File 有助于处理文件。
FileInfo 用于对文件执行操作。
FileStream 用于读,写在文件中的任何位置。
MemoryStream 用于存储在存储器流传输数据的随机访问。
Path 在执行路径信息的操作。
StreamReader 用于从字节流读取字符。
StreamWriter 用于写入字符流。
StringReader 用于从字符串缓冲区中读取。
StringWriter 用于写入字符串缓冲区。

 

FileStream类

System.IO命名空间中的FileStream类有助于读取,写入和关闭文件。 此类派生自抽象类Stream。

您需要创建一个FileStream对象来创建一个新文件或打开一个现有文件。 创建一个FileStream对象的语法如下:

Dim <object_name> As FileStream = New FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>)

例如,为创建FileStream对象读取文件namedsample.txt:

Dim f1 As FileStream = New FileStream('sample.txt', FileMode.OpenOrCreate, FileAccess.ReadWrite)
参数 描述
FileMode

FileModeenumerator定义了打开文件的各种方法。 FileMode枚举器的成员是:

  • Append:它打开一个现有文件,并将光标放在文件的末尾,或创建文件,如果该文件不存在。

  • Create:创建一个新的文件。

  • CreateNew:它指定操作系统应该创建一个新文件。

  • Open:它打开一个现有文件。

  • OpenOrCreate:它指定操作系统它应该打开一个文件,如果它存在,否则应该创建一个新文件。

  • Truncate:它打开一个现有文件,并将其大小截断为零字节。

FileAccess

FileAccessenumerators有成员:Read,ReadWriteandWrite。

FileShare

FileShareenumerators有以下成员:

  • Inheritable:它允许一个文件句柄传递继承子进程

  • None:它拒绝当前文件的共享

  • Read:它可以打开文件进行读取

  • ReadWrite:它允许打开文件进行读取和写入

  • Write:它允许打开写入文件

 

示例:

下面的程序演示使用FileStream类:

  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

当上述代码被编译和执行时,它产生了以下结果:

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中提供了简单的文件操作。 然而,为了利用System.IO类的巨大能力,你需要知道这些类的常用属性和方法。
 

我们将讨论这些类以及它们在以下部分中执行的操作。 请点击提供的链接以获取各个部分:

主题和说明

Reading from and Writing into Text files

It involves reading from and writing into text files. TheStreamReaderandStreamWriterclasses help to accomplish it.

它涉及从文本文件读取和写入。 TheStreamReaderandStreamWriterclasses有助于完成它。

Reading from and Writing into Binary files

It involves reading from and writing into binary files. TheBinaryReaderandBinaryWriterclasses help to accomplish this.

它涉及从二进制文件读取和写入。 二进制Reader和BinaryWriterclasses有助于完成这一任务。

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 - 基本控制

对象是通过使用工具箱控件在Visual Basic窗体上创建的一种用户界面元素。 事实上,在Visual Basic中,表单本身是一个对象。 每个Visual Basic控件由三个重要元素组成:

  • Properties:描述对象的属性,

  • Methods:方法导致对象做某事,

  • Events:事件是当对象做某事时发生的事情。

 

控制属性

所有Visual Basic对象可以通过设置其属性来移动,调整大小或自定义。 属性是由Visual Basic对象(例如Caption或Fore Color)持有的值或特性。

属性可以在设计时通过使用属性窗口或在运行时通过使用程序代码中的语句来设置。

Object. Property = Value
  • Object is the name of the object you're customizing.  Object是您要定制的对象的名称。

  • Property is the characteristic you want to change.  属性是您要更改的特性。

  • Value is the new property setting.  Value是新的属性设置。

例如,

Form1.Caption = 'Hello'

您可以使用属性窗口设置任何窗体属性。 大多数属性可以在应用程序执行期间设置或读取。 您可以参考Microsoft文档中与应用于它们的不同控件和限制相关的属性的完整列表。

 

控制方法

方法是作为类的成员创建的过程,它们使对象做某事。 方法用于访问或操纵对象或变量的特性。 您将在类中使用的主要有两类方法:

1、如果您使用的工具箱提供的控件之一,您可以调用其任何公共方法。 这种方法的要求取决于所使用的类。
 

2、如果没有现有方法可以执行所需的任务,则可以向类添加一个方法。

例如,MessageBox控件有一个名为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

 

控制事件

事件是通知应用程序已发生重要事件的信号。 例如,当用户单击表单上的控件时,表单可以引发Click事件并调用处理事件的过程。 有与窗体相关联的各种类型的事件,如点击,双击,关闭,加载,调整大小等。

以下是表单Load事件处理程序子例程的默认结构。 您可以通过双击代码来查看此代码,这将为您提供与表单控件相关联的所有事件的完整列表:

  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事件。 类似的方式,你可以检查存根代码点击,双击。 如果你想初始化一些变量,如属性等,那么你将这样的代码保存在Form1_Load()子程序中。 这里,重要的一点是事件处理程序的名称,默认情况下是Form1_Load,但您可以根据您在应用程序编程中使用的命名约定更改此名称。

 

基本控制

VB.Net提供了各种各样的控件,帮助您创建丰富的用户界面。 所有这些控制的功能在相应的控制类中定义。 控制类在System.Windows.Forms命名空间中定义。

下表列出了一些常用的控件:

S.N. 小部件和说明
1

Forms 形式

The container for all the controls that make up the user interface.

用于构成用户界面的所有控件的容器。

2

TextBox 文本框

It represents a Windows text box control.

它代表一个Windows文本框控件。

3

Label 标签

It represents a standard Windows label.

它代表一个标准的Windows标签。

4

Button 按钮

It represents a Windows button control.

它代表一个Windows按钮控件。

5

ListBox  列表框

It represents a Windows control to display a list of items.

它代表一个显示项目列表的Windows控件。

6

ComboBox 组合框

It represents a Windows combo box control.

它代表一个Windows组合框控件。

7

RadioButton 单选按钮

It enables the user to select a single option from a group of choices when paired with other RadioButton controls.

它使用户能够在与其他RadioButton控件配对时从一组选项中选择一个选项。

8

CheckBox 复选框

It represents a Windows CheckBox.

它代表一个Windows复选框。

9

PictureBox 图片框

It represents a Windows picture box control for displaying an image.

它表示用于显示图像的Windows画面框控件。

10

ProgressBar 进度条

It represents a Windows progress bar control.

它代表一个Windows进度条控件。

11

ScrollBar 滚动条

It Implements the basic functionality of a scroll bar control.

它实现滚动条控件的基本功能。

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.

它代表一个Windows控件,允许用户选择日期和时间,并以指定的格式显示日期和时间。

13

TreeView 树状图

It displays a hierarchical collection of labeled items, each represented by a TreeNode.

它显示标签项的分层集合,每个由树节点表示。

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.

它代表一个Windows列表视图控件,它显示可以使用四个不同视图之一显示的项目集合。

VB.Net - 对话框

有许多内置的对话框,用于Windows窗体中的各种任务,例如打开和保存文件,打印页面,向应用程序的用户提供颜色,字体,页面设置等选择。 这些内置的对话框减少了开发人员的时间和工作量。

所有这些对话框控件类继承自CommonDialog类,并覆盖基类的RunDialog()函数以创建特定对话框。

当对话框的用户调用其ShowDialog()函数时,将自动调用RunDialog()函数。

ShowDialog方法用于在运行时显示所有对话框控件。 它返回一个DialogResult枚举类型的值。 DialogResult枚举的值为:

  • Abort 中止 - returns DialogResult.Abort value, when user clicks an Abort button.  当用户单击“中止”按钮时,返回DialogResult.Abort值。

  • Cancel 取消 -returns DialogResult.Cancel, when user clicks a Cancel button.  当用户单击Ignore按钮时,返回DialogResult.Ignore。

  • Ignore 忽略 -returns DialogResult.Ignore, when user clicks an Ignore button.  返回DialogResult.No,当用户单击否按钮。

  • No  -returns DialogResult.No, when user clicks a No button.  不返回任何内容,对话框继续运行。

  • None  -returns nothing and the dialog box continues running.  返回DialogResult.OK,当用户单击确定按钮

  • OK -returns DialogResult.OK, when user clicks an OK button.  返回DialogResult.  OK,当用户点击OK键

  • Retry 重试 -returns DialogResult.Retry , when user clicks an Retry button.  当用户单击重试按钮时,返回DialogResult.Retry

  • Yes  -returns DialogResult.Yes, when user clicks an Yes button.  返回DialogResult.Yes,当用户单击是按钮

下图显示了通用对话框类继承:

上述的所有类都有相应的控件,可以在设计期间从工具箱中添加。 您可以通过以编程方式实例化类或通过使用相关控件,将这些类的相关功能包括到应用程序中。

当双击工具箱中的任何对话框控件或将控件拖动到窗体上时,它将显示在Windows窗体设计器底部的组件托盘中,但不会直接显示在窗体上。

下表列出了常用的对话框控件。 点击以下链接查看其详细信息:

 
S.N. 控制& 说明
1

ColorDialog

It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors.

它表示一个公共对话框,显示可用颜色以及允许用户定义自定义颜色的控件。

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.

它提示用户从安装在本地计算机上的字体中选择字体,并让用户选择字体,字体大小和颜色。

3

OpenFileDialog

It prompts the user to open a file and allows the user to select a file to open.

它提示用户打开文件,并允许用户选择要打开的文件。

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.

它提示用户选择保存文件的位置,并允许用户指定保存数据的文件的名称。

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.

它允许用户通过选择打印机并从Windows窗体应用程序中选择要打印的文档的哪些部分来打印文档。

VB.Net - 高级表单

在本章中,我们将研究以下概念:

  • 在应用程序中添加菜单和子菜单

  • 在表单中添加剪切,复制和粘贴功能

  • 锚定和对接控制在一种形式

  • 模态形式

 

在应用程序中添加菜单和子菜单

传统上,Menu,MainMenu,ContextMenu和MenuItem类用于在Windows应用程序中添加菜单,子菜单和上下文菜单。

现在,MenuStrip,ToolStripMenuItem,ToolStripDropDown和ToolStripDropDownMenu控件替换和添加功能到以前版本的菜单相关的控件。 但是,旧的控制类保留为向后兼容和未来使用。

让我们首先使用旧版本控件创建典型的Windows主菜单栏和子菜单,因为这些控件在旧应用程序中仍然很常用。

以下是一个示例,显示了如何使用菜单项创建菜单栏:文件,编辑,视图和项目。 文件菜单有子菜单新建,打开和保存。

让我们双击窗体,并在打开的窗口中放下面的代码。

  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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:

Windows窗体包含一组丰富的类,用于创建您自己的具有现代外观,外观和感觉的自定义菜单。 MenuStrip,ToolStripMenuItem,ContextMenuStrip控件用于有效地创建菜单栏和上下文菜单。
 

点击以下链接查看他们的详细信息:

S.N. Control & Description
1

MenuStrip

It provides a menu system for a form.

它为表单提供了一个菜单系统。

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.

它代表一个快捷菜单。

在表单中添加剪切,复制和粘贴功能

ClipBoard类公开的方法用于在应用程序中添加剪切,复制和粘贴功能。 ClipBoard类提供了在系统剪贴板上放置数据和检索数据的方法。

它有以下常用的方法:

SN 方法名称和说明
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.

指示是否有关于那就是在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格式的文本数据,根据不同的操作系统。

以下是一个示例,其中显示了如何使用Clipboard类的方法剪切,复制和粘贴数据。 执行以下步骤:

  • 在表单上添加丰富的文本框控件和三个按钮控件。

  • 将按钮的文本属性分别更改为“剪切”,“复制”和“粘贴”。

  • 双击按钮,在代码编辑器中添加以下代码:

  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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:

输入一些文本并检查按钮的工作方式。

锚定和停靠在窗体中的控件

锚定允许您设置控件的定位点位置到其容器的控件,例如,窗体的边缘。控件类 Anchor 属性允许您设置此属性的值。Anchor 属性获取或设置一个控件绑定和确定如何调整控件的大小与它的父容器的边缘。

当你锚定到窗体控件时,该控件维护它距离边缘的形式和其锚的位置,当窗体调整。

你可以从属性窗口设置控件的锚属性值︰

输入一些文本并检查按钮的工作方式。


例如,让我们在表单上添加一个Button控件,并将其anchor属性设置为Bottom,Right。 运行此窗体以查看Button控件相对于窗体的原始位置。

现在,当拉伸窗体时,Button和窗体右下角之间的距离保持不变。

控制装置的对接意味着将其对接到其容器的边缘之一。 在对接中,控制完全填充容器的某些区域。

Control类的Dock属性执行此操作。 Dock属性获取或设置哪些控件边界停靠到其父控件,并确定如何使用其父控件调整控件大小。

您可以从“属性”窗口设置控件的Dock属性值:

例如,让我们在表单上添加一个Button控件,并将其Dock属性设置为Bottom。 运行此窗体以查看Button控件相对于窗体的原始位置。

现在,当你拉伸窗体时,Button会调整窗体的大小。

 

模式窗体

模式窗体是需要关闭或隐藏的窗体,然后才能继续使用其余应用程序。 所有对话框都是模态窗体。 MessageBox也是一种模态形式。

您可以通过两种方式调用模式窗体:

  • 调用ShowDialog方法

  • 调用Show方法

让我们举一个例子,我们将创建一个模态形式,一个对话框。 执行以下步骤:

  • 将表单Form1添加到您的应用程序,并向Form1添加两个标签和一个按钮控件

  • 将第一个标签和按钮的文本属性分别更改为“欢迎使用教程点”和“输入您的名称”。 将第二个标签的文本属性保留为空。

  • 添加一个新的Windows窗体,Form2,并向Form2添加两个按钮,一个标签和一个文本框。

  • 将按钮的文本属性分别更改为“确定”和“取消”。 将标签的文本属性更改为“输入您的姓名:”。

  • 将Form2的FormBorderStyle属性设置为FixedDialog,为其提供对话框边框。

  • 将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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:

点击“输入您的姓名”按钮显示第二个表单:

单击确定按钮将控制和信息从模态形式返回到先前的形式:


VB.Net - 事件处理

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

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

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

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

  • 鼠标事件 Mouse events

  • 键盘事件 Keyboard events

 

处理鼠标事件

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

  • MouseDown -当按下鼠标按钮时发生

  • MouseEnter -当鼠标指针进入控件时发生

  • MouseHover -当鼠标指针悬停在控件上时发生

  • MouseLeave -鼠标指针离开控件时发生

  • MouseMove -当鼠标指针移动到控件上时

  • MouseUp -当鼠标指针在控件上方并且鼠标按钮被释放时发生

  • MouseWheel -它发生在鼠标滚轮移动和控件有焦点时

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

  • Buttons-表示按下鼠标按钮

  • Clicks-显示点击次数

  • Delta-表示鼠标轮旋转的定位槽的数量

  • X -指示鼠标点击的x坐标

  • Y -表示鼠标点击的y坐标

 

示例

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

  • 在表单中添加三个标签,三个文本框和一个按钮控件。

  • 将标签的文本属性分别更改为 - 客户ID,名称和地址。

  • 将文本框的名称属性分别更改为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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:

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

 

处理键盘事件

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

  • KeyDown -当按下一个键并且控件具有焦点时发生

  • KeyPress -当按下一个键并且控件具有焦点时发生

  • KeyUp -当控件具有焦点时释放键时发生

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

  • Alt -它指示是否按下ALT键/ p>

  • Control-它指示是否按下CTRL键

  • Handled-它指示事件是否被处理

  • KeyCode- 存储事件的键盘代码

  • KeyData-存储事件的键盘数据

  • KeyValue -存储事件的键盘值

  • Modifiers-指示按下哪个修饰键(Ctrl,Shift和/或Alt)

  • Shift-表示是否按下Shift键

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

  • Handled-指示KeyPress事件处理

  • KeyChar -存储对应于按下的键的字符

示例

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

  • 添加一个带有文本属性为“Age”的标签,并添加一个名为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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:

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


未完待续,下一章节,つづく

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
VB.NET New关键字相关作用剖析
VB爱好者乐园(VBGood) - 经验之谈 - VB编程的必备技巧
[VB.NET][C#.NET]WindowsForm/控件事件的先后顺序/事件方法覆写|爱工作爱生活
在VB中使用IE的WebBrowser控件
VB.net学习笔记(二十六)线程的坎坷人生
自定义VB系统控件
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服