如何用C#winform定义自己的控件

45 篇文章 0 订阅
21 篇文章 0 订阅

转载地址:https://www.cnblogs.com/feiyangqingyun/archive/2013/06/15/3137597.html

1.第一步:先准备开关按钮要使用到的背景图片,一般就两张,一张是开的,一张是关的,也可以说是开启和关闭。注意,除了把图片放到工程目录下之外,还要把控件加载到项目的资源里,步骤:右键项目-->属性-->资源-->添加现有资源

2.第二步:新建用户控件,在构造函数中设置双缓冲和背景透明以及控件大小。 

3.第三步:定义一个公共属性,这样的话外部就可以访问当前选中状态,这里也命名为Checked

4.第四步:根据当前是否选中条件分别绘制图片,在onPaint事件中

5.第五步:在Click事件

 

参考代码如下:

  public partial class mySwitchBtn : UserControl
    {
        public mySwitchBtn()
        {
            InitializeComponent();
            //设置Style支持透明背景色并且双缓冲
            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 isCheck = false;

        /// <summary>
        /// 是否选中
        /// </summary>
        public bool Checked
        {
            set { isCheck = value; this.Invalidate(); }
            get { return isCheck; }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Bitmap bitMapOn = null;
            Bitmap bitMapOff = null;
            bitMapOn = Properties.Resources.btncheckon1;
            bitMapOff = Properties.Resources.btncheckoff1;
            Graphics g = e.Graphics;
            Rectangle rec = new Rectangle(0, 0, this.Size.Width, this.Size.Height);

            if (isCheck)
            {
                g.DrawImage(bitMapOn, rec);
            }
            else
            {
                g.DrawImage(bitMapOff, rec);
            }
        }

        private void mySwitchBtn_Click(object sender, EventArgs e)
        {
            isCheck = !isCheck;
            this.Invalidate();
        }

       
    }

 

 

之后,就可以在工具栏中看到自己定义好的用户控件了(找不到的话可以搜索你的用户控件名就能看到),把它拖到你的窗体里,就可以像普通控件一样使用了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值