Winform切换开关自定义控件的实现

1、实现切换开关自定义控件
(1)、设置初始化;
(2)、扩展自定义属性;
(3)、控件重绘;
(4)、定义事件。
2、自定义控件代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomLib
{
    //指定默认事件
    [DefaultEvent("CheckedChanged")]
    public class Switch:Control
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public Switch() 
        { 
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.Selectable, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.Size = new Size(80, 30);
            this.Click += Switch_Click;
        }
        //事件
        public event EventHandler CheckedChanged;
        /// <summary>
        /// 点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Switch_Click(object sender, EventArgs e)
        {
            CheckedChanged?.Invoke(this, new EventArgs());
        }
        /// <summary>
        /// 重绘
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.HighQuality;

            //背景填充色
            var fillColor = swChecked ? trueColor : falseColor;
            //路径
            GraphicsPath path = new GraphicsPath();
            path.AddLine(Height / 2, 1, Width - Height / 2, 1);
            path.AddArc(new Rectangle(Width - Height - 1, 1, Height - 2, Height - 2), 270, 180);
            path.AddLine(Width - Height / 2, Height - 1, Height / 2, Height - 1);
            path.AddArc(new Rectangle(1, 1, Height - 2, Height - 2), 90, 180);
            //填充路径
            g.FillPath(new SolidBrush(fillColor), path);
            //显示文本
            string text = swChecked ? trueText : falseText;
            //根据开关状态,显示圆和文字
            if (swChecked)
            {
                g.FillEllipse(Brushes.White, new Rectangle(Width - Height - 1 + 2, 1 + 2, Height - 2 - 4, Height - 2 - 4));
                SizeF fontSize = g.MeasureString(text.Replace("", "开"), swFont);
                int x = (Height - 2 - 4) / 2;
                int y = (Height - (int)fontSize.Height) / 2 + 2;
                g.DrawString(text, swFont, Brushes.White, x, y);
            }
            else
            {
                g.FillEllipse(Brushes.White, new Rectangle(1 + 2, 1 + 2, Height - 2 - 4, Height - 2 - 4));
                SizeF fontSize = g.MeasureString(text.Replace("", "关"), swFont);
                int x = Width - 2 - Height / 2 - (int)fontSize.Width + 10;
                int y = (Height - (int)fontSize.Height) / 2 + 2;
                g.DrawString(text, swFont, Brushes.White, x, y);
            }
        }

        #region 属性
        private bool swChecked=false;
        [Description("开关状态"), Category("自定义")]
        public bool SwChecked
        {
            get { return swChecked; }
            set { swChecked = value; Invalidate(); }
        }

        private Color trueColor = Color.Green;
        [Description("开背景色"),Category("自定义")]
        public Color TrueColor
        {
            get { return trueColor; }
            set { trueColor = value; Invalidate(); }
        }

        private Color falseColor = Color.Gray;
        [Description("关背景色"), Category("自定义")]
        public Color FalseColor
        {
            get { return falseColor; }
            set { falseColor = value; Invalidate(); }
        }

        private string trueText= "开";
        [Description("开文字"), Category("自定义")]
        public string TrueText
        {
            get { return trueText; }
            set { trueText = value; Invalidate(); }
        }

        private string falseText= "关";
        [Description("关文字"), Category("自定义")]
        public string FalseText
        {
            get { return falseText; }
            set { falseText = value; Invalidate(); }
        }

        private Font swFont=new Font("Arial", 12, FontStyle.Bold);
        [Description("字体"), Category("自定义")]
        public Font SwFont
        {
            get { return swFont; }
            set { swFont = value; Invalidate(); }
        }
        #endregion
 
    }
}

2、控件使用和事件处理

using CustomLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomControlApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void switch1_CheckedChanged(object sender, EventArgs e)
        {
            switch1.SwChecked=!switch1.SwChecked;
        }
    }
}

3、运行结果
在这里插入图片描述
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WinForm中动态添加自定义控件的方式有多种,下面是一种常见的方法: 1. 在代码中创建一个循环,根据需要的控件数量进行迭代。例如,可以使用for循环来决定控件的数量。 2. 在循环内部,创建自定义控件的实例。可以使用自定义控件的构造函数来创建控件实例,并设置控件的属性,如名称、大小和位置。 3. 将自定义控件添加到相应的容器控件中。可以使用容器控件的Controls属性来访问和添加子控件。使用Add方法将自定义控件添加到容器控件的Controls集合中。 4. 可以为自定义控件设置相应的事件处理程序。例如,可以为自定义控件的点击事件设置一个事件处理程序,以便在点击控件时执行特定的操作。 5. 最后,将容器控件添加到主窗体中,以便在应用程序中显示这些自定义控件。 下面是一个示例代码,演示了如何动态添加自定义控件(以麦田怪圈为例): ``` for (int i = 0; i < 5; i++) { Control.Refueller r1 = new Control.Refueller(); r1.sidePanel1.Click += new EventHandler(r1click); r1.Name = "jy" + i; r1.Size = new Size(220, 281); r1.Location = new Point(220 * i, 0); r1.Show(); panel1.Controls.Add(r1); } private void r1click(object sender, EventArgs e) { MessageBox.Show(this.Name); } ``` 在上述示例中,使用了一个for循环来创建了5个麦田怪圈的自定义控件,并将它们添加到名为panel1的容器控件中。同时,为每个控件的点击事件设置了一个事件处理程序r1click,以便在点击控件时弹出一个消息框。 请注意,以上示例代码仅为演示目的,并假设已经创建了自定义控件Refueller和相应的事件处理程序r1click。你可以根据自己的需求来调整代码,并在其中添加其他所需的控件和事件处理程序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C# winform 动态添加自定义控件](https://blog.csdn.net/qq_36074218/article/details/103765069)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [winform如何添加自定义控件,如何给自定义控件添加事件](https://blog.csdn.net/xiexiaodai/article/details/125040976)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值