主要步驟有三:
創建需要支持右鍵 的控件
定義菜單欄
核心 爲控件添加菜單欄
整個過程在窗體的構造函數中實現,也就是designer.cs中的InitializeComponent方法
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);//支持右鍵 的控件
System.Windows.Forms.ContextMenu notifycontextMenu = new System.Windows.Forms.ContextMenu();//右鍵菜單欄
this.notifyIcon1.ContextMenu = notifycontextMenu;//添加菜單欄到指定控件
有以上代碼就已經實現了右鍵菜單,要豐富菜單內容則需要如下代碼,不做細說:
System.Windows.Forms.MenuItem menuItem_Hide = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem_Show = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem_Aubot = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem_Exit = new System.Windows.Forms.MenuItem();
menuItem_Hide.Index = 0;
menuItem_Hide.Text = "隱藏 ";
menuItem_Hide.Click += new System.EventHandler(this.menuItem_Hide_Click);
//
// menuItem_Show
//
menuItem_Show.Index = 1;
menuItem_Show.Text = "顯示 ";
menuItem_Show.Click += new System.EventHandler(this.menuItem_Show_Click);
//
// menuItem_Aubot
//
menuItem_Aubot.Index = 2;
menuItem_Aubot.Text = "關於 ";
menuItem_Aubot.Click += new System.EventHandler(this.menuItem_Aubot_Click);
//
// menuItem_Exit
//
menuItem_Exit.Index = 3;
menuItem_Exit.Text = "退出 ";
menuItem_Exit.Click += new System.EventHandler(this.menuItem_Exit_Click);
notifycontextMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[]{
menuItem_Hide,
menuItem_Show,
menuItem_Aubot,
menuItem_Exit
}
);
然後自己在窗體後臺代碼中添加menuItem_Aubot_Click等函數定義點擊事件處理函數。