19

I'm looking for a Split Button in .NET WinForms. The kind where one side is a button and the other side has a dropdown button.

I see them used all over in windows, like in the Visual Studio Save As window, so I figured they've got to have the control in some library.

I know there's one for toolstrips, but I need one thats usable outside of toolstrips.

Is there a Microsoft library that has one or preferably a free library? I'm using .NET 3.5

For an example: Example Button

AminM
  • 1,658
  • 4
  • 32
  • 48
jamiegs
  • 1,761
  • 2
  • 15
  • 23
  • Ha, I didn't realize that the image was a from .NET library. I just did a google image search on split button and just chose the best looking one I found. – jamiegs Oct 22 '09 at 19:18
  • 1
    The example image comes from https://wyday.com/splitbutton/ which is written in C# and has a permissive license. – user276648 Oct 17 '18 at 03:12

1 Answers1

11

You can do a simple version yourself, using the button's image. I have my own class that is derived from Button.

I set up the image (which is of a down arrow) like so:

{
    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);
}

// If you want right-mouse click to invoke the menu override the mouse up event
protected override void OnMouseUp(MouseEventArgs mevent)
{
    if ((mevent.Button & MouseButtons.Right) != 0)
        ShowMenuUnderControl();
    else
        base.OnMouseUp(mevent);
}

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

If you also wanted an icon, as in the OP, you could use a BackgroundImage and appropriate padding, like so:

this.BackgroundImageLayout = ImageLayout.None;
this.BackgroundImage = YourResources.ButtonIcon;

// Add padding so the text doesn't overlay the background image
this.Padding = new Padding(
    this.Padding.Left + this.BackgroundImage.Width,
    this.Padding.Top,
    this.Padding.Right,
    this.Padding.Bottom);

Here's a button of mine in action:
c# winforms split button with menu and arrow and icon

noelicus
  • 14,468
  • 3
  • 92
  • 111