C#实现任务栏图标

创建任务栏图标 从工具箱中向界面添加NotifyIcon控件 右键属性设置图标 双击NotifyIcon控件,添加隐藏与显示代码:

创建任务栏图标

  1. 从工具箱中向界面添加NotifyIcon控件

  2. 右键属性设置图标

  3. 双击NotifyIcon控件,添加隐藏与显示代码:

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if (this.Visible)
    {
        this.Hide();
    }
    else
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }
}
  1. 从工具箱中添加ContextMenuStrip控件

  2. 编辑菜单内容,双击添加事件

private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
    //this.close();
    notifyIcon1.Visible = false;
    Environment.Exit(0);
}
​
private void 隐藏显示ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (this.Visible)
    {
        this.Hide();
    }
    else
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }
}

如果使用了Form1_FormClosing事件最小化窗口,则不能使用this.close();方法关闭程序

  1. 关闭时提示

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    this.notifyIcon1.ShowBalloonTip(3, "提示", "已最小化运行,退出请右键", ToolTipIcon.Info);
    e.Cancel = true;
    this.Hide();
}

LICENSED UNDER CC BY-NC-SA 4.0
Comment