C#在任务栏右下角通知区域中创建图标

发布时间:2016-03-15 浏览次数:6953 文章来源:个人博客

我们有时候在最小化时候,希望的是在通知区域显示小图标,也就是说整个Form都缩小到任务栏上,这时候我们就需要用到C# 中的NotifyIcon类!


notifyIcon 的命名空间:System.Windows.Forms
程序集:System.Windows.Forms(在 system.windows.forms.dll 中)


代码如下:


#region
//创建NotifyIcon对象 
NotifyIcon notifyicon = new NotifyIcon();
//创建托盘图标对象 
Icon ico = Resource1.favicon;
//创建托盘菜单对象 
ContextMenu notifyContextMenu = new ContextMenu();
#endregion

Form1_Load事件中加入代码,如下:


private void Form1_Load(object sender, EventArgs e)
{
   this.notifyicon.Text = "小助手";//定义图标名称
   this.notifyicon.DoubleClick += notifyIcon1_DoubleClick;//双击小图标事件
   //以下是定义小图标右键出现的菜单和菜单的点击时间
   this.notifyContextMenu.MenuItems.Add("打开百度", new System.EventHandler(button2_Click));
   this.notifyContextMenu.MenuItems.Add("打开淘宝", new System.EventHandler(button1_Click));
   this.notifyContextMenu.MenuItems.Add("-");
   this.notifyContextMenu.MenuItems.Add("退出", new System.EventHandler(app_Out));
   notifyicon.ContextMenu = notifyContextMenu;
}

接下来,就是怎么样把窗口缩小到通知区域的图标和将通知区域图标放大恢复成窗口:

#region 隐藏任务栏图标、显示托盘图标
private void Form1_SizeChanged(object sender, EventArgs e)
{
  //判断是否选择的是最小化按钮 
  if (WindowState == FormWindowState.Minimized)
  {
     //托盘显示图标等于托盘图标对象 
     //注意notifyIcon1是控件的名字而不是对象的名字 
     notifyicon.Icon = ico;
     //隐藏任务栏区图标 
     this.ShowInTaskbar = false;
     //图标显示在托盘区 
     notifyicon.Visible = true;
   }
}
#endregion

#region 还原窗体
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
   //判断是否已经最小化于托盘 
   if (WindowState == FormWindowState.Minimized)
   {
     //还原窗体显示 
     WindowState = FormWindowState.Normal;
     //激活窗体并给予它焦点 
     this.Activate();
     //任务栏区显示图标 
     this.ShowInTaskbar = true;
     //托盘区图标隐藏 
     notifyicon.Visible = false;
    }
}
#endregion

这两个事件要加载到winForm的对应事件中去,这样才能触发。

这样,通知栏的图标基本就完成了~~

附上图标右键菜单事件的代码:

    

#region 打开百度(地址那里需要有Http://)
private void button1_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("百度的地址");
}
#endregion
    
#region 打开淘宝
private void button2_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("淘宝地址");
}
#endregion

#region 退出
private void app_Out(object sender,EventArgs e)
{
    this.Close();  
}
#endregion
key-word
C#小图标 C#右下角图标 C#窗口最小化 C#ICO