一 托盘通知
NotifyIcon托盘通知:
程序可以在通知区创建一个通知图标。一般地,可以提示一个气泡通知,右键菜单支持。
准备:需要一个图标(*.ico),用于显示在通知区。如果没有ico格式,可以将png图片转成ico。
演示:在项目中添加托盘通知。
① 设置文本Text;
② 选择图标Icon;
默认地,图标资源保存在Form1.resx里,其实也可以使用全局图标资源。
运行程序,观察托盘区的图标。
二 气泡通知
气泡通知:BalloonTip
演示:点击下载时,开启一个下载任务。下载完成时,在托盘处显示气泡通知。点击气泡通知时,显示主窗口。
代码实现:
notifyIcon1.ShowBalloonTip(
timeout,
title,
text,
icon);
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace 气泡通知 {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void 退出ToolStripMenuItem_Click(object sender, EventArgs e){Application.Exit();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){if(e.CloseReason==CloseReason.UserClosing){e.Cancel = true;this.Hide();}}private void 显示主窗口ToolStripMenuItem_Click(object sender, EventArgs e){this.Show();this.Activate();}//模拟下载private void button1_Click(object sender, EventArgs e){this.Hide();Thread th = new Thread(this.DownloadTask);th.Start();}private void DownloadTask(){for(int i=0;i<5;i++){Thread.Sleep(1000);int percent = i * 100 / 5;Console.WriteLine("模拟下载任务:{0}%", i);}OnTaskFinished();}//下载任务完成时,在托盘处显示气泡通知private void OnTaskFinished(){if(this.InvokeRequired){this.Invoke(new Action(this.OnTaskFinished));return;}this.notifyIcon1.ShowBalloonTip(0,"下载完成","下载XXXX.ZIP已经完成",ToolTipIcon.Info);}//用户点击气泡通知时,显示主窗口private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e){this.Show();this.Activate();}} }