定义类时,可以为数据类型定义蓝图。 这实际上并不定义任何数据,但它定义了类名的含义,即类的对象将包含什么以及可以对这样的对象执行什么操作。
对象是类的实例。 构成类的方法和变量称为类的成员。
类的定义以关键字Class开头,后跟类名称; 和类体,由End Class语句结束。 以下是类定义的一般形式:
- [ <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是一个适用于类的属性列表。 可选的。
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类,它有三个数据成员,长度,宽度和高度:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Volume of Box1 : 210
- Volume of Box2 : 1560
类的成员函数是一个函数,它的定义或其原型在类定义中像任何其他变量一样。 它对它所属的类的任何对象进行操作,并且可以访问该对象的类的所有成员。
成员变量是对象的属性(从设计角度),它们被保持为私有以实现封装。 这些变量只能使用public成员函数访问。
让我们把上面的概念设置并获得类中不同类成员的值:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Volume of Box1 : 210
- Volume of Box2 : 1560
类构造函数是每当我们创建该类的新对象时执行的类的特殊成员子类。 构造函数具有名称New,并且没有任何返回类型。
下面的程序解释了构造函数的概念:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Object is being created
- Length of line : 6
默认构造函数没有任何参数,但如果需要,构造函数可以有参数。 这样的构造函数称为参数化构造函数。 此技术可帮助您在创建对象时为其分配初始值,如以下示例所示:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Object is being created, length = 10
- Length of line set by constructor : 10
- Length of line set by setLength : 6
析构函数是一个类的特殊成员Sub,只要它的类的对象超出范围,它就被执行。
析构函数名为Finalize,它既不能返回值也不能接受任何参数。 析构函数在释放程序之前释放资源非常有用,比如关闭文件,释放内存等。
析构函数不能继承或重载。
下面的例子解释析构函数的概念:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Object is being created
- Length of line : 6
- Object is being deleted
我们可以使用Shared关键字将类成员定义为静态。 当我们将一个类的成员声明为Shared时,意味着无论创建多少个对象,该成员只有一个副本。
关键字“共享”意味着类只存在一个成员实例。 共享变量用于定义常量,因为它们的值可以通过调用类而不创建它的实例来检索。
共享变量可以在成员函数或类定义之外初始化。 您还可以在类定义中初始化共享变量。
您还可以将成员函数声明为共享。 这样的函数只能访问共享变量。 共享函数甚至在创建对象之前就存在。
以下示例演示了共享成员的使用:
- 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
当上述代码被编译和执行时,它产生了以下结果:
Value of variable num: 3
面向对象编程中最重要的概念之一是继承。 继承允许我们根据另一个类来定义一个类,这使得更容易创建和维护应用程序。 这也提供了重用代码功能和快速实现时间的机会。
在创建类时,程序员可以指定新类应该继承现有类的成员,而不是编写完全新的数据成员和成员函数。 这个现有类称为基类,新类称为派生类。
类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。
VB.Net中用于创建派生类的语法如下:
- <access-specifier> Class <base_class>
- ...
- End Class
- Class <derived_class>: Inherits <base_class>
- ...
- End Class
考虑一个基类Shape和它的派生类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
当上述代码被编译和执行时,它产生了以下结果:
Total area: 35
派生类继承基类成员变量和成员方法。 因此,应该在创建子类之前创建超类对象。 超类或基类在VB.Net中被称为MyBase
以下程序演示了这一点:
- ' 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
当上述代码被编译和执行时,它产生了以下结果:
- Length: 4.5
- Width: 7.5
- Area: 33.75
- Cost: 2362.5
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的语法如下所示:
- Try
- [ tryStatements ]
- [ Exit Try ]
- [ Catch [ exception [ As type ] ] [ When expression ]
- [ catchStatements ]
- [ Exit Try ] ]
- [ Catch ... ]
- [ Finally
- [ finallyStatements ] ]
- End Try
您可以列出多个catch语句以捕获不同类型的异常,以防您的try块在不同情况下引发多个异常。
在.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关键字实现。 以下是在零除条件时抛出异常的示例:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- Exception caught: System.DivideByZeroException: Attempted to divide by zero.
- at ...
- Result: 0
您还可以定义自己的异常。 用户定义的异常类派生自ApplicationException类。 以下示例演示了这一点:
- 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
当上述代码被编译和执行时,它产生了以下结果:
TempIsZeroException: Zero Temperature found
如果它是直接或间接从System.Exception类派生的,你可以抛出一个对象。
你可以在catch块中使用throw语句来抛出当前对象:
Throw [ expression ]
下面的程序说明了这一点:
- 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
当上述代码被编译和执行时,它产生了以下结果:
- A custom exception is being thrown here...
- Now inside the Finally Block
Afileis是存储在具有特定名称和目录路径的磁盘中的数据的集合。 当打开文件进行读取或写入时,它变为astream。
流基本上是通过通信路径的字节序列。 有两个主要流:输入流和输出流。 输入流用于从文件读取数据(读取操作)和输出流用于写入文件(写入操作)。
System.IO命名空间具有用于对文件执行各种操作的各种类,例如创建和删除文件,读取或写入文件,关闭文件等。
下表显示了System.IO命名空间中一些常用的非抽象类:
I / O类 | 描述 |
---|---|
BinaryReader | 读取二进制流的基本数据。 |
BinaryWriter | 以二进制格式写入原始数据。 |
BufferedStream | 对于字节流的临时存储。 |
Directory | 有助于操纵的目录结构。 |
DirectoryInfo | 用于对目录进行操作。 |
DriveInfo | 提供了驱动器的信息。 |
File | 有助于处理文件。 |
FileInfo | 用于对文件执行操作。 |
FileStream | 用于读,写在文件中的任何位置。 |
MemoryStream | 用于存储在存储器流传输数据的随机访问。 |
Path | 在执行路径信息的操作。 |
StreamReader | 用于从字节流读取字符。 |
StreamWriter | 用于写入字符流。 |
StringReader | 用于从字符串缓冲区中读取。 |
StringWriter | 用于写入字符串缓冲区。 |
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枚举器的成员是:
|
FileAccess | FileAccessenumerators有成员:Read,ReadWriteandWrite。 |
FileShare | FileShareenumerators有以下成员:
|
下面的程序演示使用FileStream类:
- 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
当上述代码被编译和执行时,它产生了以下结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
上面的示例在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文件和目录的能力。 |
对象是通过使用工具箱控件在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的方法,它在下面的代码片段中调用:
- 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
事件是通知应用程序已发生重要事件的信号。 例如,当用户单击表单上的控件时,表单可以引发Click事件并调用处理事件的过程。 有与窗体相关联的各种类型的事件,如点击,双击,关闭,加载,调整大小等。
以下是表单Load事件处理程序子例程的默认结构。 您可以通过双击代码来查看此代码,这将为您提供与表单控件相关联的所有事件的完整列表:
- 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事件。 类似的方式,你可以检查存根代码点击,双击。 如果你想初始化一些变量,如属性等,那么你将这样的代码保存在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列表视图控件,它显示可以使用四个不同视图之一显示的项目集合。 |
有许多内置的对话框,用于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窗体应用程序中选择要打印的文档的哪些部分来打印文档。 |
在本章中,我们将研究以下概念:
在应用程序中添加菜单和子菜单
在表单中添加剪切,复制和粘贴功能
锚定和对接控制在一种形式
模态形式
传统上,Menu,MainMenu,ContextMenu和MenuItem类用于在Windows应用程序中添加菜单,子菜单和上下文菜单。
现在,MenuStrip,ToolStripMenuItem,ToolStripDropDown和ToolStripDropDownMenu控件替换和添加功能到以前版本的菜单相关的控件。 但是,旧的控制类保留为向后兼容和未来使用。
让我们首先使用旧版本控件创建典型的Windows主菜单栏和子菜单,因为这些控件在旧应用程序中仍然很常用。
以下是一个示例,显示了如何使用菜单项创建菜单栏:文件,编辑,视图和项目。 文件菜单有子菜单新建,打开和保存。
让我们双击窗体,并在打开的窗口中放下面的代码。
- 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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:
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类的方法剪切,复制和粘贴数据。 执行以下步骤:
在表单上添加丰富的文本框控件和三个按钮控件。
将按钮的文本属性分别更改为“剪切”,“复制”和“粘贴”。
双击按钮,在代码编辑器中添加以下代码:
- 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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:
输入一些文本并检查按钮的工作方式。
锚定允许您设置控件的定位点位置到其容器的控件,例如,窗体的边缘。控件类 Anchor 属性允许您设置此属性的值。Anchor 属性获取或设置一个控件绑定和确定如何调整控件的大小与它的父容器的边缘。
当你锚定到窗体控件时,该控件维护它距离边缘的形式和其锚的位置,当窗体调整。
你可以从属性窗口设置控件的锚属性值︰
输入一些文本并检查按钮的工作方式。
例如,让我们在表单上添加一个Button控件,并将其anchor属性设置为Bottom,Right。 运行此窗体以查看Button控件相对于窗体的原始位置。
现在,当拉伸窗体时,Button和窗体右下角之间的距离保持不变。
控制装置的对接意味着将其对接到其容器的边缘之一。 在对接中,控制完全填充容器的某些区域。
Control类的Dock属性执行此操作。 Dock属性获取或设置哪些控件边界停靠到其父控件,并确定如何使用其父控件调整控件大小。
您可以从“属性”窗口设置控件的Dock属性值:
例如,让我们在表单上添加一个Button控件,并将其Dock属性设置为Bottom。 运行此窗体以查看Button控件相对于窗体的原始位置。
现在,当你拉伸窗体时,Button会调整窗体的大小。
您可以通过两种方式调用模式窗体:
调用ShowDialog方法
调用Show方法
让我们举一个例子,我们将创建一个模态形式,一个对话框。 执行以下步骤:
将表单Form1添加到您的应用程序,并向Form1添加两个标签和一个按钮控件
将第一个标签和按钮的文本属性分别更改为“欢迎使用教程点”和“输入您的名称”。 将第二个标签的文本属性保留为空。
添加一个新的Windows窗体,Form2,并向Form2添加两个按钮,一个标签和一个文本框。
将按钮的文本属性分别更改为“确定”和“取消”。 将标签的文本属性更改为“输入您的姓名:”。
将Form2的FormBorderStyle属性设置为FixedDialog,为其提供对话框边框。
将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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:
点击“输入您的姓名”按钮显示第二个表单:
单击确定按钮将控制和信息从模态形式返回到先前的形式:
事件基本上是一个用户操作,如按键,点击,鼠标移动等,或某些事件,如系统生成的通知。 应用程序需要在事件发生时对其进行响应。
单击按钮,或在文本框中输入某些文本,或单击菜单项,都是事件的示例。 事件是调用函数或可能导致另一个事件的操作。
事件处理程序是指示如何响应事件的函数。
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。
将按钮的文本属性更改为“提交”。
在代码编辑器窗口中添加以下代码:
- 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工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:
尝试在文本框中输入文字,并检查鼠标事件:
以下是与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事件。
添加以下代码以处理文本框txtID的KeyUP事件。
当使用Microsoft Visual Studio工具栏上的“开始”按钮执行并运行上述代码时,将显示以下窗口:
如果将age或ID的文本留空,或输入一些非数字数据,则会出现一个警告消息框,并清除相应的文本:
未完待续,下一章节,つづく
联系客服