C# Windows应用窗体用户自定义控件--开关实现

在学习C# Windows应用窗体时,利用用户自定义控件实现了一个小的开关控件。
参考:https://www.cnblogs.com/feiyangqingyun/archive/2013/06/15/3137597.htmlhtml

先准备了两个好看的开关图片:
这里写图片描述git

将图片资源导入项目
打开Properties下Resources.rex:
这里写图片描述
选择图像:
这里写图片描述
添加现有文件:(将准备好的图片添加)
这里写图片描述
添加完成,能够看到多了一个Resources文件夹,里面就是咱们刚刚添加的图片:
这里写图片描述github

自定义用户控件
在项目右键添加用户控件:
这里写图片描述web

输入名称:
这里写图片描述ide

进入代码:
这里写图片描述svg

在构造函数中设置双缓冲和背景透明以及控件大小。 函数

public SwitchTest()
         {
            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);                          this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.BackColor = Color.Transparent;
            this.Cursor = Cursors.Hand;
            this.Size = new Size(87, 27);
          }

定义一个公共属性来标志开关工具

bool isSwitch = false;

重写OnPaint学习

protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Rectangle rec = new Rectangle(0, 0, this.Size.Width, this.Size.Height);
            if (isSwitch)
            {
                g.DrawImage(Properties.Resources.switchon, rec);
            }
            else
            {
                g.DrawImage(Properties.Resources.switchoff, rec);
            }
        }

重写鼠标点击测试

protected override void OnMouseClick(MouseEventArgs e)
        {
            isSwitch = !isSwitch;
            this.Invalidate();
            base.OnMouseClick(e);
        }

此时用户自定义控件完成,来测试一下。
先生成解决方案:
这里写图片描述

生成解决方案完成,到一个form设计,你会发现工具箱多了咱们刚刚的用户自定义控件:
这里写图片描述
拖拽一个放到form上:
这里写图片描述
运行,点击:
这里写图片描述

源代码github:https://github.com/yuace/CSharp–Mycontroller