1. 程式人生 > >C#winform中怎麼將程式最小化到系統托盤

C#winform中怎麼將程式最小化到系統托盤

1.在form中新增一個NotifyIcon控制元件     
 
2.把87.ico這個圖示放在/bin/Debug目錄下  
 
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
 
namespace 將程式最小化到系統托盤  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
 
        private void Form1_Load(object sender, EventArgs e)  
        {  
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);  
            notifyIcon1.Icon = new Icon("87.ico");//指定一個圖示     
            notifyIcon1.Visible = false;  
            notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);  
            this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged);     
      
 
        }  
 
        private void Form1_SizeChanged(object sender, EventArgs e)  
        {  
            if (this.WindowState == FormWindowState.Minimized)//最小化     
            {  
                this.ShowInTaskbar = false;  
                this.notifyIcon1.Visible = true;  
            }     
 
        }  
 
              private void notifyIcon1_Click(object sender, EventArgs e)  
        {  
            if (this.WindowState == FormWindowState.Minimized)  
                this.WindowState = FormWindowState.Normal;  
            this.Activate();  
            this.notifyIcon1.Visible = false;  
            this.ShowInTaskbar = true;     
 
        }  
 
    }  
}

如何將上下文選單與 Windows 窗體 NotifyIcon 元件關聯:

Windows 窗體 NotifyIcon 元件在工作列的狀態通知區域中顯示一個圖示。通常,應用程式允許您右擊此圖示將命令傳送到它表示的應用程式。通過將 ContextMenu 元件與 NotifyIcon 元件關聯,您可以將此功能新增到應用程式中。

注意   如果您希望應用程式啟動時以最小化顯示,同時在工作列中顯示 NotifyIcon 元件的一個例項,請將主窗體的 WindowState 屬性設定為 Minimized 並確保將 NotifyIcon 元件的 Visible 屬性設定為 true

在設計時將上下文選單與 NotifyIcon 元件關聯

  1. 向窗體新增 NotifyIcon 元件,並設定重要屬性,如 IconVisible 屬性。
  2. 向 Windows 窗體新增 ContextMenu 元件。

    向表示您希望在執行時使其可用的命令的上下文選單新增選單項。這也是向這些選單項新增選單增強功能的好時機,如訪問鍵。

  3. NotifyIcon 元件的 ContextMenu 屬性設定為已新增的上下文選單。

    設定此屬性後,單擊工作列上的圖示時將顯示上下文選單。

以程式設計方式將上下文選單與 NotifyIcon 元件關聯

  1. 使用應用程式所需的任何屬性設定(NotifyIcon 元件的 IconVisible 屬性,ContextMenu
    元件的選單項),例項化 NotifyIcon 元件和 ContextMenu 元件。
  2. NotifyIcon 元件的 ContextMenu 屬性設定為已新增的上下文選單。

    設定此屬性後,單擊工作列上的圖示時將顯示上下文選單。