我想将其放置在按下按钮的位置,它将显示已选择哪个按钮。但是,我希望在按钮上进行新选择后消失。我做了一个自定义按钮(下面的代码)。当我单击按钮时,按钮确实会立即更改颜色,但是当我单击第二个按钮时,它不会将背景色更改回原始颜色。
按钮:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace InformationBookFinal.User_Control
{
public class FlatButton : Button
{
public FlatButton()
{
BackColor = Color.DodgerBlue;
ForeColor = Color.White;
CurrentBackColor = BackColor;
}
private Color CurrentBackColor;
private Color onHoverBackColor = Color.DarkOrchid;
public Color OnHoverBackColor
{
get { return onHoverBackColor; }
set { onHoverBackColor = value; Invalidate(); }
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
CurrentBackColor = onHoverBackColor;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
CurrentBackColor = BackColor;
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs mevent)
{
base.OnMouseDown(mevent);
CurrentBackColor = Color.RoyalBlue;
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
CurrentBackColor = BackColor;
Invalidate();
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
pevent.Graphics.FillRectangle(new SolidBrush(CurrentBackColor), 0, 0, Width, Height);
TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
TextRenderer.DrawText(pevent.Graphics, Text, Font, new Point(Width + 3, Height / 2), ForeColor, flags);
}
}
}
按钮操作:
private void flatButton2_Click(object sender, EventArgs e)
{
flatButton1.BackColor = Color.DodgerBlue;
flatButton1.Hide();
flatButton1.Show();
}
private void flatButton1_Click(object sender, EventArgs e)
{
flatButton1.BackColor = Color.Pink;
}
答案 0 :(得分:1)
设置BackColor值时,不会更新在Paint方法中使用的CurrentBackColor值。
因此,请尝试覆盖该属性:
public override Color BackColor {
get {
return base.BackColor;
}
set {
base.BackColor = value;
CurrentBackColor = value;
this.Invalidate();
}
}