1. 程式人生 > 其它 >C# WinForm 去除Button按鈕選中時的邊框效果

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;
        }

    }
}

  

最終的效果為:

普通的按鈕設定為如下樣式:

在點選、啟用時會有無用的邊框:

設定新的邊框大小和邊框顏色屬性後:

這是我們的新按鈕並沒有如下的多餘的邊框:

完成

如有問題請聯絡QQ: var d=["1","2","3","4","5","6","7","8","9"]; var pass=d[8]+d[6]+d[0]+d[8]+d[2]+d[0]+d[4]+d[3]+d[2];