Skip to content

Instantly share code, notes, and snippets.

@DaniSagan
Created October 16, 2019 19:45
Show Gist options
  • Save DaniSagan/6f8fad01a839379a568632c4acfe347c to your computer and use it in GitHub Desktop.
Save DaniSagan/6f8fad01a839379a568632c4acfe347c to your computer and use it in GitHub Desktop.
WinForms switch control
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Switch
{
public partial class CustomCheckBox : CheckBox
{
[Browsable(true)]
[Description("Ask before change")]
[Category("CustomCheckBox")]
public bool AskBeforeChange { get; set; } = false;
[Browsable(true)]
[Description("Ask before change")]
[Category("CustomCheckBox")]
public string MessageBeforeChange { get; set; } = string.Empty;
public CustomCheckBox()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
Padding = new Padding(6);
}
protected override void OnPaint(PaintEventArgs e)
{
this.OnPaintBackground(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (GraphicsPath path = new GraphicsPath())
{
int d = Padding.All;
int radius = this.Height - 2 * d;
path.AddArc(d, d, radius, radius, 90, 180);
path.AddArc(this.Width - radius - d, d, radius, radius, -90, 180);
path.CloseFigure();
e.Graphics.FillPath(Checked ? Brushes.DarkGray : Brushes.LightGray, path);
radius = Height - 1;
Rectangle rect =
Checked ? new Rectangle(Width - radius - 1, 0, radius, radius)
: new Rectangle(0, 0, radius, radius);
e.Graphics.FillEllipse(Checked ? Brushes.Green : Brushes.WhiteSmoke, rect);
}
}
protected override void OnClick(EventArgs e)
{
if (AskBeforeChange)
{
DialogResult result = MessageBox.Show(MessageBeforeChange, "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
if (result != DialogResult.Cancel)
{
Checked = !Checked;
}
}
}
protected override void OnCheckedChanged(EventArgs e)
{
}
[Browsable(false)]
public new bool AutoCheck => false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment