首先我必须说代码运行完美。
但我担心使用这种方式 img 变量是多余的,因为我还有变量 _originalImage。
类顶部的代码:
private bool _DisplayFocusCues = true;
private Image _originalImage;
private Image _clickImage;
private Image img;
public CustomButton()
{
this.FlatStyle = FlatStyle.Flat;
this.FlatAppearance.BorderSize = 0;
this.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); // Transparent
this.FlatAppearance.MouseDownBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on click
this.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on hover
this.DisplayFocusCues = false;
// Assume Properties.Resources.YourImageResource is the resource identifier for your image
img = ResizeImage(Properties.Resources.icons8_record_32, 50, 50);
this.Image = img;
this.Size = img.Size;
_originalImage = img;
}
然后在 OnMouseUp 事件中
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
_originalImage = img;
this.Image = _originalImage;
}
我使用 img 变量的原因是因为在 OnMouseUp 事件中以这种方式使用它时,它会产生单击按钮更改颜色的按钮单击效果。
如果没有 img 变量,当我每次单击按钮时,它都会使按钮颜色越来越暗,并且永远不会返回到按钮原始颜色。
我还没有测试以下代码,但我认为这会起作用。
private bool _DisplayFocusCues = true;
private Image _originalImage;
private Image _clickImage;
public CustomButton()
{
this.FlatStyle = FlatStyle.Flat;
this.FlatAppearance.BorderSize = 0;
this.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); // Transparent
this.FlatAppearance.MouseDownBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on click
this.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on hover
this.DisplayFocusCues = false;
// Assume Properties.Resources.YourImageResource is the resource identifier for your image
this.Image = ResizeImage(Properties.Resources.icons8_record_32, 50, 50);
this.Size = this.Image.Size;
_originalImage = this.Image;
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
base.OnMouseUp(mevent);
this.Image = _originalImage;
}
protected override void OnMouseDown(MouseEventArgs mevent)
{
base.OnMouseDown(mevent);
if (_clickImage != null)
this.Image = _clickImage;
}