C# 创建右键菜单和编程

1.在控件上右键,弹出菜单


1.在工具箱里拖一个ContextMenuStrip控件到Form上,设置属性,示例如下图


C# 创建右键菜单和编程_第1张图片


2.将你要设置右键菜单的控件的ContextMenuStrip属性关联为刚刚创建的contextMenuStrip




2.右键菜单相应的编程


1.对控件的MouseUp事件编程,比如这里对ListBox控件编程


private void listBoxBusRoutes_MouseUp(object sender, MouseEventArgs e)//鼠标右键菜单
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {                
                int index = listBoxBusRoutes.IndexFromPoint(e.Location);
                if (index >= 0 && index < listBoxBusRoutes.Items.Count)
                {
                    listBoxBusRoutes.SelectedIndex = index;
                    this.contextMenuStrip.Visible = true;
                }
                else
                    this.contextMenuStrip.Visible = false;
            }            
        }


2.右键菜单点击事件

private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.contextMenuStrip.Visible = false;
            switch (e.ClickedItem.Text)
            {
                case "删除":/*......*/;break;
                case "编辑":/*......*/ ; break;
                default: /*......*/break;
            }
        }



参考资料:

http://www.cnblogs.com/netlyf/archive/2011/04/04/2005155.html




你可能感兴趣的:(C# 创建右键菜单和编程)