[C#] NotifyIcon (System Tray)

說明

每個 NotifyIcon 元件會在狀態區域中顯示一個圖示。 NotifyIcon 元件的主要屬性為 IconVisibleIcon 屬性會設定在狀態區域中顯示的圖示。 若要顯示圖示,Visible 屬性必須設定為 true

NotifyIcon



建置

NotifyIcon 元件

  • 將工具箱中的 NotifyIcon 元件拉到 Form 中。


  • 雙擊新增的元件會產生滑鼠雙擊事件,在其中加入所需事件,Sample 為顯示 Form 至前景。
private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }

    this.Activate();
    this.Focus();
}


  • 新增 BalloonTipClicked、DoubleClick 事件,在NotifyBallonTip上按下Click或著雙擊 NotifyIcon,就將Form開啟出來
this.NotifyIcon1.BalloonTipClicked += new System.EventHandler(this.NotifyIcon1_BalloonTipClicked);
this.NotifyIcon1.DoubleClick+= new System.EventHandler(this.NotifyIcon1_BalloonTipClicked);

private void NotifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }

    this.Activate();
    this.Focus();
}


  • 監聽 Form 的 X 按鈕事件,將 Form 縮小而不是關閉程式。
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormClosingFunction);

private void FormClosingFunction(object sender, FormClosingEventArgs e)
{
    if (this.WindowState != FormWindowState.Minimized)
    {
        // 須將 e.Cancel 設為 true,防止 Form 被關閉。
        e.Cancel = true;

        this.Hide();
        this.WindowState = FormWindowState.Minimized;
    }
}


ContextMenuStrip 元件

此元件可設定針對 NotifyIcon 右鍵的 Menu 內容。

  • 將工具箱中的 ContextMenuStrip 元件拉到 Form 中。

ContextMenuStripContextMenuStrip


  • 指定 NotifyIcon 的 ContextMenuScript 至剛拉進去的元件。

ContextMenuStrip


  • 加入 Menu 的選項,可直接輸入或右鍵點擊 ContextMenuScript 元件 → 編輯項目 新增 Menu 項目。


  • 雙擊上述新增的 Menu 項目會產生點擊事件,Simple 為開啟、關閉顯示 Form 的語法。
private void MenuItemOpen_Click(object sender, EventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }

    this.Activate();
    this.Focus();
}

private void MenuItemExit_Click(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Minimized;
    this.Close();
}

留言

這個網誌中的熱門文章

[Android] Glide 教學

[ 教程 - 破解 ] IOS 10.2 JB 教學

[教學] AdMob for Android App