Toggle Switch Control in Windows Forms

前端 未结 1 1956
一整个雨季
一整个雨季 2020-12-06 03:19

I am designing a Toggle Switch control using CheckBox, but currently my control only draws a circle. How can I draw round shapes like below image and how can I

相关标签:
1条回答
  • 2020-12-06 03:52

    I know this is a winforms question. But you may want to take a look at Toggle Switches or read more about Universal Windows App Components.

    Anyway, here is an answer for Windows forms developers. It shows how we can customize rendering of a check box to have such appearance.

    Currently you are drawing only an ellipse, it's quiet a toggle button. But if you want to show it like the below image, you should first draw a round shape for background, then based on Checked value draw the check circle. Using the codes in Example part of the answer you can have a CheckBox with such UI:

    Example

    The important thing about this sample is it's completely a CheckBox control and supports check using mouse and keyboard, also supports data-binding and all other standard features of CheckBox. The code is not perfect, but is a good start point to have a yes/no toggle switch:

    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Windows.Forms;
    public class MyCheckBox : CheckBox
    {
        public MyCheckBox()
        {
            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 (var path = new GraphicsPath())
            {
                var d = Padding.All;
                var r = this.Height - 2 * d;
                path.AddArc(d, d, r, r, 90, 180);
                path.AddArc(this.Width - r - d, d, r, r, -90, 180);
                path.CloseFigure();
                e.Graphics.FillPath(Checked ? Brushes.DarkGray : Brushes.LightGray, path);
                r = Height - 1;
                var rect = Checked ? new Rectangle(Width - r - 1, 0, r, r)
                                   : new Rectangle(0, 0, r, r);
                e.Graphics.FillEllipse(Checked ? Brushes.Green : Brushes.WhiteSmoke, rect);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题