C# WinForm 去除Button按钮选中时的边框效果

C# WinForm 去除Button按钮选中时的边框效果

WinForm 去除 Button 按钮 选中时 的 边框 效果

 

-------------------------------------------------

  ----------文章末尾看效果-------------

-------------------------------------------------

 

参考文章:

https://stackoverflow.com/questions/9399215/c-sharp-winforms-custom-button-unwanted-border-when-form-unselected

但是不完全可以使用,改善后的代码为:

 

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

namespace YingCaiEdu.Control
{
    public class YceButton : Button
    {
        int borderSize;
        /// <summary>
        /// 获取或设置一个值,该值指定按钮周围的边框的大小(以像素为单位)。
        /// </summary>
        [Browsable(true), Description("边框颜色"), Category("自定义分组")]
        public int BorderSize
        {
            get { return borderSize; }
            set
            {
                borderSize = value;
                this.Invalidate();
            }
        }

        Color borderColor;
        /// <summary>
        /// 获取或设置一个值,该值指定按钮周围的边框的大小(以像素为单位)。
        /// </summary>
        [Browsable(true), Description("边框颜色"), Category("自定义分组")]
        public Color BorderColor
        {
            get { return borderColor; }
            set
            {
                borderColor = value;
                this.Invalidate();
            }
        }

        public YceButton() : base()
        {
            //base.TabStop = false;
            base.FlatStyle = FlatStyle.Flat;
            base.FlatAppearance.BorderSize = 0;
            base.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255);

            BorderSize = 1;
            BorderColor = Color.Silver;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            //1 (0,0,-1,-1)
            //2 (1,1,-2,-2)
            //3 (1,1,-3,-3)
            //4 (2,2,-4,-4)
            //5 (2,2,-5,-5)
            //6 (3,3,-6,-6)
            if (BorderSize > 0)
                if (BorderSize == 1)
                    e.Graphics.DrawRectangle(new Pen(BorderColor, BorderSize), 0, 0, this.Width - BorderSize, this.Height - BorderSize);
                else
                    e.Graphics.DrawRectangle(new Pen(BorderColor, BorderSize), BorderSize / 2, BorderSize / 2, this.Width - BorderSize, this.Height - BorderSize);
        }

        protected override bool ShowFocusCues
        {
            get => false;
        }

    }
}

  

 

最终的效果为:

普通的按钮设置为如下样式:

 

 在点击、激活时会有无用的边框:

 

 

设置新的边框大小和边框颜色属性后:

这是我们的新按钮并没有如下的多余的边框:

 

完成

 

posted @ 2021-07-05 14:58  爱恋的红尘  阅读(544)  评论(0编辑  收藏  举报