主要步骤有三:
创建需要支持右键 的控件
定义菜单栏
核心 为控件添加菜单栏
整个过程在窗体的构造函数中实现,也就是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等函数定义点击事件处理函数。