VB.NET语言 制作带动画图标的托盘程序

VB.NET阿木 发布于 2025-05-28 11 次阅读


VB.NET【1】制作带动画图标的托盘程序【2】教程

托盘程序(也称为系统托盘或托盘图标程序)是一种常驻系统托盘区的应用程序,可以提供快速访问、通知或后台服务。在VB.NET中,我们可以轻松创建一个带动画图标的托盘程序。本文将详细介绍如何使用VB.NET和Windows API【3】来实现这样一个程序。

环境准备

在开始编写代码之前,请确保您的计算机上已安装以下软件:

- Visual Studio【4】 2019或更高版本
- .NET Framework【5】 4.8或更高版本

创建托盘程序

1. 创建项目

1. 打开Visual Studio,选择“创建新项目”。
2. 在“创建新项目”对话框中,选择“Windows窗体应用程序”模板,并命名为“托盘程序”。
3. 点击“创建”按钮。

2. 添加托盘图标

1. 在“托盘程序”项目中,找到“Properties”文件夹,打开“AssemblyInfo.vb”文件。
2. 在文件顶部添加以下代码:

vb
Imports System.Drawing
Imports System.Windows.Forms

Public Class AssemblyInfo
Inherits System.Reflection.AssemblyInfo
Public Overrides Sub SetCustomAttribute(ByVal attribute As System.ReflectionCustomAttributes)
MyBase.SetCustomAttribute(New System.Windows.Forms.AssemblyIconAttribute(My.Resources.icon))
End Sub
End Class

3. 在“托盘程序”项目中,添加一个名为“Icon【6】.ico”的图标文件到“Resources”文件夹中。

3. 添加托盘图标控件

1. 在窗体上添加一个`NotifyIcon【7】`控件。
2. 设置`NotifyIcon`的`Visible`属性为`True`。

vb
Private notifyIcon As New NotifyIcon()
notifyIcon.Visible = True

4. 添加动画图标

1. 创建一个名为`AnimatedIcon`的新类,继承自`NotifyIcon`。
2. 在`AnimatedIcon`类中,添加以下代码:

vb
Public Class AnimatedIcon
Inherits NotifyIcon

Private animationFrames As Integer = 0
Private frameInterval As Integer = 100 ' 每帧间隔时间(毫秒)
Private iconList As List(Of Icon)

Public Sub New()
iconList = New List(Of Icon)()
iconList.Add(My.Resources.icon1)
iconList.Add(My.Resources.icon2)
iconList.Add(My.Resources.icon3)
iconList.Add(My.Resources.icon4)
iconList.Add(My.Resources.icon5)
iconList.Add(My.Resources.icon6)
iconList.Add(My.Resources.icon7)
iconList.Add(My.Resources.icon8)
iconList.Add(My.Resources.icon9)
iconList.Add(My.Resources.icon10)
End Sub

Public Overrides Sub OnPaint(ByVal e As PaintEventArgs)
MyBase.OnPaint(e)
If animationFrames < iconList.Count Then
Me.Icon = iconList(animationFrames)
animationFrames += 1
Me.Refresh()
Threading.Thread.Sleep(frameInterval)
End If
End Sub
End Class

3. 在窗体代码中,将`NotifyIcon`替换为`AnimatedIcon`:

vb
Private animatedIcon As New AnimatedIcon()
animatedIcon.Visible = True

5. 添加退出菜单项

1. 在窗体上添加一个`ContextMenuStrip【8】`控件。
2. 添加一个名为“退出”的菜单项。
3. 设置菜单项的`Click`事件处理程序:

vb
Private Sub exitMenuItem_Click(sender As Object, e As EventArgs) Handles exitMenuItem.Click
animatedIcon.Visible = False
Application.Exit()
End Sub

4. 将菜单项添加到`ContextMenuStrip`:

vb
Private contextMenuStrip As New ContextMenuStrip()
Dim exitMenuItem As New ToolStripMenuItem("退出")
contextMenuStrip.Items.Add(exitMenuItem)
exitMenuItem.Click += AddressOf exitMenuItem_Click
animatedIcon.ContextMenuStrip = contextMenuStrip

运行程序

1. 保存所有代码。
2. 运行程序,您将看到一个带动画图标的托盘程序。

总结

本文介绍了如何使用VB.NET和Windows API创建一个带动画图标的托盘程序。通过添加`NotifyIcon`控件、自定义动画图标和退出菜单项,我们可以实现一个功能丰富的托盘程序。希望本文对您有所帮助。