1. 创建项目
新建一个C# Windows窗体应用程序,命名为SystemTray。
2. 添加NotifyIcon控件
拷贝一个图标文件到项目文件夹,拖动工具箱中的NotifyIcon控件到窗体中,在NotifyIcon1控件的属性页中将(Name)项改为TrayNotifyIcon,在Icon项中添加刚才拷贝的图标,Text项添加“系统托盘示例”。.
3. 更改主窗体图标和标题
在主窗体属性页中,在Icon项中添加刚才拷贝的图标,将Text项改为“系统托盘示例”。
4. 更改主窗体类名
在主窗体属性页中,将(Name)项改为SystemTrayForm。
5. 添加单击托盘事件响应代码
在SystemTray类中添加显示和隐藏两种方法,代码如下:
// 显示窗体及任务栏图标
private void ShowMainForm()
{
this.Visible = true; // 窗体可见
this.WindowState = FormWindowState.Normal; // 窗体状态为正常
TrayNotifyIcon.Visible = true; // 托盘图标可见
this.ShowInTaskbar = true; // 在任务栏显示窗体
}
// 隐藏窗体和任务栏图标
private void HideMainForm()
{
this.WindowState = FormWindowState.Minimized; // 最小化时隐藏窗体
this.Visible = false; // 窗体不可见
this.TrayNotifyIcon.Visible = true; // 图标在任务栏区域可见
this.ShowInTaskbar = false; // 不在在任务栏显示窗体
}
在TrayNotifyIcon控件事件页MouseClick项中添加TrayNotifyIconMouseClick事件,并添加如下代码:
// 判断是否单击鼠标左键
if (e.Button == MouseButtons.Left)
{
// 切换显示状态
if(this.WindowState == FormWindowState.Minimized)
{
ShowMainForm();
}
else
{
HideMainForm();
}
}
6. 添加单击最小化框事件响应代码
在TrayNotifyIcon控件事件页MouseClick项中添加SystemTrayFormDeactivate事件,并添加如下代码:
// 判断是否为最小化状态
if (this.WindowState == FormWindowState.Minimized)
{
HideMainForm();
}
7. 程序启动时隐藏窗体
将主窗体属性页中的WindowsState项改为Minimized,以使程序启动时最小化窗口,将ShowInTaskbar项改为False,使程序窗体不显示在任务栏中。
8. 第一次显示窗体时使窗体居于屏幕中心
在SystemTrayForm方法中加入下面的代码实现窗体居中。
// 设置窗口位置为屏幕居中
Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
this.SetDesktopLocation((rect.Width - this.DefaultSize.Width) / 2, (rect.Height -this.DefaultSize.Height) / 2);
完整的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SystemTray
{
public partial class SystemTrayForm : Form
{
#region 初始化窗体
public SystemTrayForm()
{
InitializeComponent();
#region 窗体居中
Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
this.SetDesktopLocation((rect.Width - this.DefaultSize.Width) / 2, (rect.Height -this.DefaultSize.Height) / 2);
#endregion
}
#endregion
#region 显示窗体及任务栏图标
private void ShowMainForm()
{
this.Visible = true; // 窗体可见
this.WindowState = FormWindowState.Normal; // 窗体状态为正常
TrayNotifyIcon.Visible = true; // 托盘图标可见
this.ShowInTaskbar = true; // 在任务栏显示窗体
}
#endregion
#region 隐藏窗体和任务栏图标
private void HideMainForm()
{
this.WindowState = FormWindowState.Minimized; // 最小化时隐藏窗体
this.Visible = false; // 窗体不可见
this.TrayNotifyIcon.Visible = true; // 图标在任务栏区域可见
this.ShowInTaskbar = false; // 不在在任务栏显示窗体
}
#endregion
#region 鼠标单击托盘事件响应
private void TrayNotifyIconMouseClick(object sender, MouseEventArgs e)
{
// 判断是否单击鼠标左键
if (e.Button == MouseButtons.Left)
{
// 切换显示状态
if (this.WindowState == FormWindowState.Minimized)
{
ShowMainForm();
}
else
{
HideMainForm();
}
}
}
#endregion
#region 最小化事件响应
private void SystemTrayFormDeactivate(object sender, EventArgs e)
{
// 判断是否为最小化状态
if (this.WindowState == FormWindowState.Minimized)
{
HideMainForm();
}
}
#endregion
}
}
留言列表