在c# WinForm中为按钮或拆分按钮添加上下文菜单

本文关键字:按钮 拆分 添加 上下文 菜单 WinForm | 更新日期: 2023-09-27 18:16:16

在c#对话框中,我想添加一个具有双重行为的按钮,即保存和另存为。当用户单击按钮的右上角时,应该出现一个小的上下文菜单,指示另存为选项。

在c# WinForm中为按钮或拆分按钮添加上下文菜单

SplitButton将是实现这一目标的最佳选择。您将在这里找到SplitButton的代码和使用它的示例。

您可以拥有自己的按钮类,派生自Button,具有几个覆盖,将简单地完成工作。只需传递一个ContextMenuStrip (splitMenuStrip在我的代码下面)。

我设置图像(这是一个向下的箭头),像这样:

{
    this.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
    this.Image = YourResources.split_button; // Your down-arrow image
    this.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
}

protected override void OnClick(EventArgs e)
{
    var clickPos = this.PointToClient(new System.Drawing.Point(MousePosition.X, MousePosition.Y));
    // If click is over the right-hand portion of the button show the menu
    if (clickPos.X > (Size.Width - Image.Width))
        ShowMenuUnderControl()
    else
        base.OnClick(e);
}

// Raise the context menu
public void ShowMenuUnderControl()
{
    splitMenuStrip.Show(this, new Point(0, this.Height), ToolStripDropDownDirection.BelowRight);
}

要了解更全面的答案,请查看我对类似/相同问题的回答。