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;
}
}
}
最終的效果為:
普通的按鈕設置為如下樣式:

在點擊、激活時會有無用的邊框:

設置新的邊框大小和邊框顏色屬性后:
這是我們的新按鈕並沒有如下的多余的邊框:

完成
