WindowForm components MenuStrip, ContextMenuStrip

1. MenuStrip menu control ---- a container containing multiple menu items
1. Property
Name, Dock layout, Items menu item collection
Items
DropDownItems sub-menu collection
ShortcutKeys shortcut key Alt +F at the same time after the item text (Text&F)
Ctrl + There is no need to add an
item ToolStripMenuItem
submenu item ToolStripMenuItem
icon in the menu item ToolStripMenuItem after the N item text —the associated picture collection control ImageList
2. Manually add—for each menu item, register a response for it—Click the
menu item, it has sub-menus, just No need to register a response for it

Add menu item

Insert picture description here

private void FrmMenuStrip_Load(object sender, EventArgs e)
{
    
    
    //代码添加菜单项
    ToolStripMenuItem miStudent = new ToolStripMenuItem();
    miStudent.Name = "miStudent";       //名称
    miStudent.Text = "学生管理(&M)";    //显示文本
    //它下面还有子菜单 
    ToolStripMenuItem miAddStudent = new ToolStripMenuItem();
    miAddStudent.Name = "miAddStudent";
    miAddStudent.Text = "新增学生";
    miAddStudent.Click += MiAddStudent_Click;   //响应事件 
    miStudent.DropDownItems.Add(miAddStudent);  //添加子菜单
    menuStrip1.Items.Add(miStudent);            //添加主菜单
}
//点击事件
private void MiAddStudent_Click(object sender, EventArgs e)
{
    
    
     MForms.FrmAddStudent fAddStudent = new MForms.FrmAddStudent();
     fAddStudent.MdiParent = this;   //设置当前窗体的父窗体
     fAddStudent.Show();             //Mdi容器不支持ShowDialog()
 }

Move the mouse over to automatically display the drop-down menu
Insert picture description here

private void FrmContextMenuStrip_Load(object sender, EventArgs e)
{
    
    
    menuStrip1.Items[0].MouseHover += FrmContextMenuStrip_MouseHover;
}
//鼠标移过事件
private void FrmContextMenuStrip_MouseHover(object sender, EventArgs e)
{
    
    
    if (sender is ToolStripMenuItem)
    {
    
    
        ToolStripMenuItem item = sender as ToolStripMenuItem;
        if (item.HasDropDownItems && !item.DropDown.Visible)//有菜单项 且 菜单项不可见
        {
    
    
            item.ShowDropDown();
        }
    }
}

2. ContextMenuStrip right-click menu item

Use depends on a form or controlInsert picture description here

 //设置背景色为红色
 private void miRed_Click(object sender, EventArgs e)
 {
    
    
     this.BackColor = Color.Red;
 }
 //设置背景色为绿色
 private void miGreen_Click(object sender, EventArgs e)
 {
    
    
     this.BackColor = Color.Green;
 }
 //新画面
  private void miAddStudent_Click(object sender, EventArgs e)
  {
    
    
      MForms.FrmAddStudent fStudent = new MForms.FrmAddStudent();	//学生新增页面
      fStudent.Show();
  }

Guess you like

Origin blog.csdn.net/asdasd1fdsyrt/article/details/113956338