首页 > 编程语言 >将Winform窗体程序缩到System tray的示例代码

将Winform窗体程序缩到System tray的示例代码

时间:2023-09-22 21:11:17浏览次数:51  
标签:控件 sender 示例 void System private 窗体 tray

网上有很多将Winform窗体缩到 System tray的示例, 但多数不好用.
这里是一个简单示例, 使用了Visual studio自带的 NotifyIcon 控件和一个快捷菜单 contextMenuStrip控件.

增加一个 contextMenuStrip 控件, 新增两个菜单项: 显示界面和退出系统.
增加一个 NotifyIcon 控件, 设置它的图标, 并绑定上面的菜单组件.

C#代码示例:

public partial class Form1 : Form
{
private readonly string APPLICATION_NAME = "我的程序";
private bool appShouldClose = false;

public Form1()
{
    InitializeComponent();
}

/// <summary>
/// 恢复显示主界面
/// </summary>
private void showUI()
{
    this.Show();
    this.WindowState = FormWindowState.Normal;
    notifyIcon1.Visible = false;
}

/// <summary>
/// trayIcon 双击鼠标用来显示主界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    showUI();
}

/// <summary>
/// trayIcon 的快捷菜单项[显示主界面]的处理函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripMenuItemOpen_Click(object sender, EventArgs e)
{
    showUI();
}

/// <summary>
/// trayIcon 的快捷菜单项[退出系统]的处理函数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripMenuItemExit_Click(object sender, EventArgs e)
{
    var result = MessageBox.Show("请确认是否要退出系统?", "请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (result == DialogResult.Yes)
    {
        appShouldClose = true;
        this.Close();
    }
}

/// <summary>
/// 缩小窗体到 sys tray
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (appShouldClose)
    {
        //nothing
    }
    else if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;
        this.WindowState = FormWindowState.Minimized;
        this.Hide();
        notifyIcon1.Visible = true;
        notifyIcon1.ShowBalloonTip(1000, APPLICATION_NAME, "已最小化到系统托盘", ToolTipIcon.Info);
    }
}
}

标签:控件,sender,示例,void,System,private,窗体,tray
From: https://www.cnblogs.com/harrychinese/p/17723372.html

相关文章