美文网首页
C# ContextMenuStrip内容菜单

C# ContextMenuStrip内容菜单

作者: 技术老小子 | 来源:发表于2025-02-16 05:10 被阅读0次

摘要


ContextMenuStrip 替换了 ContextMenu。 可以将 a ContextMenuStrip 与任何控件相关联,右键单击会自动显示快捷菜单。 可以使用 Show 方法以编程方式显示 ContextMenuStripContextMenuStrip 支持可取消的 OpeningClosing 事件来处理动态填充和多单击情形。 ContextMenuStrip 支持图像、菜单项检查状态、文本、访问键、快捷方式和级联菜单。

正文


属性

AutoClose 获取或设置一个值,该值指示 ToolStripDropDown 控件是否应在失去激活状态时自动关闭。 (继承自 ToolStripDropDown)
Items 获取属于 ToolStrip 的所有项。 (继承自 ToolStrip)

方法

Close() 关闭 ToolStripDropDown 控件。 (继承自 ToolStripDropDown)
Show() 在其默认位置显示 ToolStripDropDown 控件。 (继承自 ToolStripDropDown)

做一个右键事件

image.png
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button== MouseButtons.Right)
    {
        cmnuMain.Show(this, new Point(e.X, e.Y));
        this.Text = e.X + ":" + e.Y;
    }
}

private void cmnuMain_Add_Click(object sender, EventArgs e)
{
    MessageBox.Show("添加成功!");
}

image.png

内容菜单一般用于右键操作时,增加一些额外事件功能,在ListView中用的也比较多。

代码生成菜单

image.png
private void btnShow_Click(object sender, EventArgs e)
{
    cmnuMain.Items.Clear();
    ToolStripMenuItem tool1 =new ToolStripMenuItem();
    tool1.Text = "红色";
    tool1.Tag = Color.Red;
    cmnuMain.Items.Add(tool1);
    ToolStripMenuItem tool2 = new ToolStripMenuItem();
    tool2.Text = "黄色";
    tool2.Tag = Color.Yellow;
    cmnuMain.Items.Add(tool2);

    ToolStripMenuItem tool3 = new ToolStripMenuItem();
    tool3.Text = "蓝色";
    tool3.Tag = Color.Blue;
    cmnuMain.Items.Add(tool3);

    tool1.Click += Tool_Click;
    tool2.Click += Tool_Click;
    tool3.Click += Tool_Click;

    cmnuMain.Show(btnShow,new Point(0, btnShow.Height));

}

private void Tool_Click(object? sender, EventArgs e)
{
    btnShow.BackColor = (Color)((ToolStripMenuItem)sender).Tag;
}

相关文章

网友评论

      本文标题:C# ContextMenuStrip内容菜单

      本文链接:https://www.haomeiwen.com/subject/rucdpjtx.html