精通VB,10个实用程序设计实例,助你提升编程技能

admin 全知百科 2024-11-09 22 0

在编程的世界里,Visual Basic(VB)是一个历史悠久且广泛使用的编程语言,它以其易学易用的特性,深受初学者和开发者的喜爱,VB语言简洁明了,支持多种编程范式,包括过程化、面向对象和事件驱动编程,我们将通过10个实用的VB程序设计实例,帮助你提升编程技能。

1、简单计算器

Module SimpleCalculator
    Sub Main()
        Console.WriteLine("欢迎使用简单计算器")
        Dim num1 As Double = CDbl(Console.ReadLine())
        Dim num2 As Double = CDbl(Console.ReadLine())
        Dim operator As Char = Console.ReadKey().KeyChar
        Dim result As Double = 0
        Select Case operator
            Case "+"
                result = num1 + num2
            Case "-"
                result = num1 - num2
            Case "*"
                result = num1 * num2
            Case "/"
                If num2 <> 0 Then
                    result = num1 / num2
                Else
                    Console.WriteLine("除数不能为0")
                    Return
                End If
            Case Else
                Console.WriteLine("未知操作符")
                Return
        End Select
        Console.WriteLine("结果是:" & result)
    End Sub
End Module

2、数据库连接与查询

Imports System.Data.SqlClient
Module DatabaseQuery
    Sub Main()
        Dim connectionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True"
        Dim connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand("SELECT * FROM Customers", connection)
        Dim adapter As New SqlDataAdapter(command)
        Dim table As New DataTable()
        Try
            adapter.Fill(table)
            Console.WriteLine("成功连接数据库并查询数据")
            Console.WriteLine(table)
        Catch ex As Exception
            Console.WriteLine("数据库连接或查询失败:" & ex.Message)
        End Try
        connection.Close()
    End Sub
End Module

3、图片处理与显示

精通VB,10个实用程序设计实例,助你提升编程技能

Imports System.Drawing
Imports System.Windows.Forms
Module ImageProcessing
    Sub Main()
        Dim openFileDialog As New OpenFileDialog()
        Dim saveFileDialog As New SaveFileDialog()
        Dim image As Image
        openFileDialog.InitialDirectory = "C:\"
        openFileDialog.Filter = "图片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png"
        openFileDialog.FilterIndex = 2
        openFileDialog.RestoreDirectory = True
        If openFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            image = Image.FromFile(openFileDialog.FileName)
            Dim form As New Form()
            Dim pictureBox As New PictureBox()
            pictureBox.Image = image
            form.Controls.Add(pictureBox)
            form.ShowDialog()
        End If
        If saveFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            image.Save(saveFileDialog.FileName)
        End If
    End Sub
End Module

4、网络爬虫

Imports System.Net
Imports System.IO
Module WebScraper
    Sub Main()
        Dim url As String = "http://example.com"
        Dim request As HttpWebRequest = WebRequest.Create(url)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim buffer(2048) As Byte
        Dim count As Integer = stream.Read(buffer, 0, buffer.Length)
        Dim html As String = Encoding.UTF8.GetString(buffer, 0, count)
        Console.WriteLine(html)
    End Sub
End Module

5、游戏开发

Imports System
Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Input
Module Game1
    Private game As New Game()
    Private window As Window
    Public Class Game : Inherits Game
        Private graphicsDevice As GraphicsDevice
        Private spriteBatch As SpriteBatch
        Public Sub New()
            MyBase.New()
            IsMouseVisible = True
        End Sub
        Protected Overrides Sub Initialize()
            MyBase.Initialize()
            graphicsDevice = GraphicsDevice
            spriteBatch = New SpriteBatch(graphicsDevice)
        End Sub
        Protected Overrides Sub LoadContent()
            MyBase.LoadContent()
            '加载游戏资源
        End Sub
        Protected Overrides Sub UnloadContent()
            MyBase.UnloadContent()
            '卸载游戏资源
        End Sub
        Protected Overrides Sub DrawGame(ByVal gameTime As GameTime)
            graphicsDevice.Clear(Color.CornflowerBlue)
            '绘制游戏内容
            MyBase.DrawGame(gameTime)
        End Sub
        Protected Overrides Sub Update(ByVal gameTime As GameTime)
            '更新游戏状态
            MyBase.Update(gameTime)
        End Sub
    End Class
End Module

6、多线程编程

Imports System.Threading
Module ThreadPoolExample
    Sub Main()
        ThreadPool.QueueUserWorkItem(Function()
                                         Console.WriteLine("线程1开始执行")
                                         Console.WriteLine("线程1执行完毕")
                                     End Function)
        ThreadPool.QueueUserWorkItem(Function()
                                         Console.WriteLine("线程2开始执行")
                                         Console.WriteLine("线程2执行完毕")
                                     End Function)
        Console.WriteLine("主线程开始执行")
        Console.WriteLine("主线程执行完毕")
    End Sub
End Module

7、XML文件读写

Imports System.Xml
Module XmlExample
    Sub Main()
        Dim xmlDocument As XmlDocument = New XmlDocument()
        Dim xmlNode As XmlNode = xmlDocument.CreateNode(XmlNodeType.Element, "root", Nothing)
        xmlDocument.AppendChild(xmlNode)
        xmlNode.AppendChild(xmlDocument.CreateElement("child", "value1"))
        xmlNode.AppendChild(xmlDocument.CreateElement("child", "value2"))
        xmlDocument.Save("example.xml")
        Dim xmlReader As XmlTextReader = New XmlTextReader("example.xml")
        While xmlReader.Read()
            If xmlReader.NodeType = XmlNodeType.Element Then
                Console.WriteLine(xmlReader.Name)
                Console.WriteLine(xmlReader.GetAttribute("value"))
            End If
        End While
    End Sub
End Module

8、邮件发送

Imports System.Net.Mail
Module EmailSender
    Sub Main()
        Dim smtpServer As New SmtpClient("smtp.example.com")
        Dim mail As New MailMessage()
        mail.From = New MailAddress("sender@example.com")
        mail.To.Add("receiver@example.com")
        mail.Subject = "邮件主题"
        mail.Body = "邮件内容"
        smtpServer.Send(mail)
    End Sub
End Module

9、JSON数据解析

Imports System
Imports System.IO
Imports Newtonsoft.Json
Module JsonParser
    Sub Main()
        Dim jsonText As String = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"
        Dim jsonObj As JObject = JObject.Parse(jsonText)
        Dim name As String = jsonObj("name").ToString()
        Dim age As Integer = jsonObj("age").ToObject(Of Integer)()
        Dim city As String = jsonObj("city").ToString()
        Console.WriteLine("Name: " & name)
        Console.WriteLine("Age: " & age)
        Console.WriteLine("City: " & city)
    End Sub
End Module

10、事件驱动编程

Imports System.Windows.Forms
Module EventDriven
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MessageBox.Show("按钮1被点击")
        End Sub
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            MessageBox.Show("按钮2被点击")
        End Sub
    End Class
End Module

通过这些实例,你可以了解到VB在不同领域的应用,包括基础的数值计算、数据库操作、图形界面设计、网络通信、游戏开发、多线程处理、文件操作、邮件发送、JSON解析以及事件驱动编程,这些实例不仅能够帮助你加深对VB语言的理解,还能提升你的编程能力和实践技能。

Visual Basic(VB)是一种强大的编程语言,它在许多领域都有着广泛的应用,从简单的计算器到复杂的网络爬虫,从游戏开发到多线程编程,VB都能够胜任,通过本文中的10个实用程序设计实例,你将能够更好地掌握VB语言的使用,提升你的编程技能,无论你是VB新手还是老手,这些实例都将是你提升编程能力的宝贵资源。

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

分享:

扫一扫在手机阅读、分享本文

评论

最近发表