C#实现 Winform 程序在系统托盘显示图标 & 开机自启动

实现步骤

  • 创建 NotifyIcon 控件并设置属性;
  • 编写 NotifyIcon 响应控制事件;
  • 在主窗体的Load事件中将 NotifyIcon 添加到系统托盘;
  • 程序退出时,移除系统托盘的 NotifyIcon;

NotifyIcon 控件,通常用于在系统托盘中显示图标,通过使用它就可以我们想要的效果。

属性 描述
Icon 在系统托盘中显示的图标
Text 鼠标悬停在图标时显示的文本
Visible 指定是否可见

常用方法

方法 描述
ShowContextMenu 在系统托盘上下文菜单中显示指定的菜单

添加控件(拖拽方式)

将NotifyIcon和一个ContextMenuStrip控件。拖到主窗体中可以修改控件名称

  • NotifyIcon 托盘图标
  • ContextMenuStrip 托盘图标右击弹出的菜单
    C#实现 Winform 程序在系统托盘显示图标 & 开机自启动

设置控件

点击 ContextMenuStrip 右上方的三角图标 -> 编辑项,弹出项信合编辑器
添加右健菜单信息
C#实现 Winform 程序在系统托盘显示图标 & 开机自启动

添加主窗体事件

在最小化或关闭主窗体时,显示在任务栏托盘区域,实现了单击关闭时,不真正关闭程序,而是将主界面隐藏HIDE掉,同时开始显示托盘菜单。
C#实现 Winform 程序在系统托盘显示图标 & 开机自启动

//  只有Form_Closing事件中 e.Cancel可以用。 //  你的是Form_Closed事件。 Form_Closed事件时窗口已关了 ,Cancel没用了; //  Form_Closing是窗口即将关闭时询问你是不是真的关闭才有Cancel事件  private void MainWindow_FormClosing(object sender, FormClosingEventArgs e) {      // 注意判断关闭事件reason来源于窗体按钮,否则用菜单退出时无法退出!     if (e.CloseReason == CloseReason.UserClosing)     {         //取消"关闭窗口"事件         e.Cancel = true; // 取消关闭窗体           //使关闭时窗口向右下角缩小的效果         this.WindowState = FormWindowState.Minimized;         this.mainNotifyIcon.Visible = true;         //this.m_cartoonForm.CartoonClose();         this.Hide();         return;     } } 

实现双击托盘打开主程序

//  添加托盘程序 //  版本更新自1.0.1 private void mainNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) {     if (this.Visible)     {         this.WindowState = FormWindowState.Minimized;         this.mainNotifyIcon.Visible = true;         this.Hide();     }     else     {         this.Visible = true;         this.WindowState = FormWindowState.Normal;         this.Activate();     } } 
 //  添加托盘程序右键菜单项 //  版本更新自1.0.1 //  退出 //  添加日期 --  2015-07-29 21:44 private async void toolStripMenuItemQuit_Click(object sender, EventArgs e) {     if (MessageBox.Show("你确定要退出?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Yes)     {          this.mainNotifyIcon.Visible = false;         this.Close();         this.Dispose();         System.Environment.Exit(System.Environment.ExitCode);         } } 

代码方式添加

using System; using System.Windows.Forms;   namespace Fountain.WinForm.NotifyDemo {     public partial class FormMain : Form     {         /// <summary>         /// 通知控件         /// </summary>         private NotifyIcon notifyIcon = new NotifyIcon();         /// <summary>         /// 通知控件显示菜单         /// </summary>         private ContextMenuStrip contextMenuStrip = new ContextMenuStrip();         /// <summary>         /// 构造方法         /// </summary>         public FormMain()         {             InitializeComponent();         }         /// <summary>         /// 窗体加载         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void FormMain_Load(object sender, EventArgs e)         {             this.InitializeNotifyMenu();             this.notifyIcon.Text = this.Text;             this.notifyIcon.Visible = true;             this.notifyIcon.Icon = this.Icon;             this.notifyIcon.ContextMenuStrip = this.contextMenuStrip;             this.notifyIcon.DoubleClick += notifyIcon_DoubleClick;         }         /// <summary>         /// 托盘菜单         /// </summary>         private void InitializeNotifyMenu()         {             try             {                 contextMenuStrip.Items.Clear();                 ToolStripMenuItem showMenuItem = new ToolStripMenuItem("显示界面");                 showMenuItem.Tag = "显示";                 showMenuItem.Click += new EventHandler(ShowMenuItem_Click);                 contextMenuStrip.Items.Add(showMenuItem);                   ToolStripMenuItem sboutMenuItem = new ToolStripMenuItem("关于");                 sboutMenuItem.Tag = "关于";                 sboutMenuItem.Click += new EventHandler(AboutMenuItem_Click);                 contextMenuStrip.Items.Add(sboutMenuItem);                   ToolStripMenuItem exitMenuItem = new ToolStripMenuItem("退出");                 exitMenuItem.Tag = "退出";                 exitMenuItem.Click += new EventHandler(ExistMenuItem_Click);                 contextMenuStrip.Items.Add(exitMenuItem);             }             catch(Exception exception)              {                 throw new Exception(exception.Message);             }         }         /// <summary>         /// 右击任务栏图标         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void notifyIcon_DoubleClick(object sender, EventArgs e)         {             try             {                 if (this.WindowState == FormWindowState.Normal)                 {                     this.WindowState = FormWindowState.Minimized;                     this.Hide();                 }                 else if (this.WindowState == FormWindowState.Minimized)                 {                     this.Show();                     this.WindowState = FormWindowState.Normal;                     this.Activate();                 }             }             catch (Exception objException)             {                 throw new Exception(objException.Message);             }         }         /// <summary>         /// 显示         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void ShowMenuItem_Click(object sender, EventArgs e)         {             try             {                 this.Show();                 this.WindowState = FormWindowState.Normal;                 this.Activate();             }             catch (Exception objException)             {                 throw new Exception(objException.Message);             }         }         /// <summary>         /// 关于         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void AboutMenuItem_Click(object sender, EventArgs e)         {             try             {             }             catch (Exception objException)             {                 MessageBox.Show(objException.Message);             }         }         /// <summary>         /// 退出         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void ExistMenuItem_Click(object sender, EventArgs e)         {             try             {                 if (MessageBox.Show("你确定要退出程序吗?","提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)                 {                     this.notifyIcon.Visible = false;                     this.notifyIcon.Dispose();                     this.Dispose();                     Application.Exit();                 }             }             catch (Exception objException)             {                 MessageBox.Show(objException.Message);             }         }         /// <summary>         /// 主窗体关闭         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void FormMain_FormClosing(object sender, FormClosingEventArgs e)         {             try             {                 e.Cancel = true;                 this.Hide();                 this.notifyIcon.Dispose();             }             catch (Exception objException)             {                 MessageBox.Show(objException.Message);             }         }         /// <summary>         /// 窗体大小变化         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void FormMain_Resize(object sender, EventArgs e)         {             if (this.WindowState == FormWindowState.Minimized)             {                 this.ShowInTaskbar = false;                 this.Hide();                 this.notifyIcon.Visible = true;             }         }     } } 

系统开机自启动应用程序

using Microsoft.Win32; using System; using System.Diagnostics; using System.Windows.Forms;   namespace Fountain.WinForm.NotifyDemo {     public partial class FormMain : Form     {         /// <summary>         /// 构造方法         /// </summary>         public FormMain()         {             InitializeComponent();         }         /// <summary>         /// 窗体加载         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void FormMain_Load(object sender, EventArgs e)         {              //一般不会放这个事件里去设置,而且设置时需要看下注册表要有没有写入成功有的话可以不用调了,偷懒多调一次也没事             string applictionName = Process.GetCurrentProcess().MainModule.ModuleName;             string applictionPath = Process.GetCurrentProcess().MainModule.FileName;             #region 当前登陆用户的注册表启动项             RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");             registryKey.SetValue(applictionName, applictionPath);             #endregion             #region 所有用户的注册表启动项             //RegistryKey registryKey = Registry.LocalMachine.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");             //registryKey.SetValue(applictionName, applictionPath);             #endregion         }     } } 

发表评论

评论已关闭。

相关文章