Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Last active October 24, 2019 15:52
Show Gist options
  • Save derekantrican/b1f61bb9efefec338f10dc1ace2c306c to your computer and use it in GitHub Desktop.
Save derekantrican/b1f61bb9efefec338f10dc1ace2c306c to your computer and use it in GitHub Desktop.
A simple split button for C# WinForms
using System;
using System.Windows.Forms;
using System.Drawing;
namespace SplitButton
{
public class SplitButton : Button
{
public ContextMenuStrip SplitMenuStrip = new ContextMenuStrip() { ShowImageMargin = false };
private string currentText;
public SplitButton()
{
if (this.SplitMenuStrip.Items.Count > 0)
this.Text = this.SplitMenuStrip.Items[0].Text;
this.TextAlign = ContentAlignment.MiddleLeft;
SplitMenuStrip.ItemClicked += SplitMenuStrip_ItemClicked;
}
private void SplitMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
this.currentText = e.ClickedItem.Text;
this.Text = this.currentText;
}
protected override void OnPaint(PaintEventArgs pevent)
{
if (string.IsNullOrEmpty(currentText))
{
if (this.SplitMenuStrip.Items.Count > 0)
this.Text = this.SplitMenuStrip.Items[0].Text;
}
else
this.Text = currentText;
base.OnPaint(pevent);
Graphics g = pevent.Graphics;
Rectangle bounds = ClientRectangle;
Point middle = new Point(Convert.ToInt32(bounds.Left + bounds.Width - 10), Convert.ToInt32(bounds.Top + bounds.Height / 2));
//if the width is odd - favor pushing it over one pixel right.
middle.X += (bounds.Width % 2);
Point[] arrow = new[] { new Point(middle.X - 2, middle.Y - 1), new Point(middle.X + 3, middle.Y - 1), new Point(middle.X, middle.Y + 2) };
if (Enabled)
g.FillPolygon(SystemBrushes.ControlText, arrow);
else
g.FillPolygon(SystemBrushes.ButtonShadow, arrow);
}
protected override void OnClick(EventArgs e)
{
SplitMenuStrip.Show(this, new Point(0, this.Height), ToolStripDropDownDirection.BelowRight);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment