C#最小化到系统托盘代码

1.在主窗体中添加一个 NotifyIcon 控件-notifyIcon1
2.在主窗体中添加一个 ContextMenu 控件-contextMenu1,并添加菜单项
3.设置 notifyIcon1 的属性:
将notifyIcon1.ContextMenu 设置为 contextMenu1
    notifyIcon1.Visible = true
    notifyIcon1.Icon 设置到一个图标文件

3.处理主窗体的closing事件,即关闭主窗体时就最小化到系统托盘


private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
                switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                case CloseReason.TaskManagerClosing:
                case CloseReason.WindowsShutDown:
                    e.Cancel = false;
                    break;
                default:
                    e.Cancel = true;
                    break;

            }

            this.WindowState = FormWindowState.Minimized;
            this.Visible = false;
            this.notifyIcon1.Visible = true;


}


4.在系统托盘中主窗体的图标上单击右键,出现上下文菜单(contextMenu1)
在某个菜单项的方法中,确保可以恢复主窗体

private void menuItem1_Click(object sender, System.EventArgs e)
{
    this.Visible = true; //恢复主窗体

}


在某个菜单项的方法中,确保可以退出程序
private void menuItem2_Click(object sender, System.EventArgs e)
{
    Application.Exit();
}


5.也可以不使用上下文菜单来恢复窗体,直接处理notifyIcon1的DoubleClik事件(双击恢复主窗体)
private void notifyIcon1_DoubleClick(object sender, System.EventArgs e)
{
    if (this.Visible == false)
    {
        this.Visible = true;
    }
}

posted @ 2011-04-11 20:08  surfshark  阅读(480)  评论(0编辑  收藏  举报