我正在创建一个测试C#WinForm应用程序,我有一个关闭按钮。将鼠标悬停在按钮上时,BackColor会变为较浅的颜色。当您停止在其上方悬停时,该按钮会变回背景颜色。单击该按钮后,它将变为白色,放开后,将更改为背景颜色。我的问题是,如果有人盘旋并且它改变了悬停颜色,那么有人点击并再次更改颜色,如果他们将鼠标拖离按钮,我可以将其更改回悬停颜色吗?
代码:
public Form1()
{
InitializeComponent();
bunifuImageButton1.MouseEnter += bunifuImageButton1_MouseHover;
bunifuImageButton1.MouseLeave += bunifuImageButton1_MouseLeave;
bunifuImageButton1.MouseDown += bunifuImageButton1_MouseDown;
bunifuImageButton1.MouseUp += bunifuImageButton1_MouseUp;
}
private void bunifuImageButton1_MouseHover(object sender, EventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.Highlight;
}
private void bunifuImageButton1_MouseLeave(object sender, EventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.HotTrack;
}
private void bunifuImageButton1_MouseDown(object sender, EventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.Control;
}
private void bunifuImageButton1_MouseUp(object sender, EventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.HotTrack;
}
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
答案 0 :(得分:0)
您可以跟踪鼠标是否已关闭,如果鼠标已关闭且离开按钮,则将颜色更改为悬停颜色。
但是有一个问题,因为如果鼠标停止,MouseLeave
不会触发,所以你需要检查MouseMove
事件上的鼠标位置,如下所示:
private bool isMouseDown;
private void bunifuImageButton1_MouseHover(object sender, EventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.Highlight;
}
private void bunifuImageButton1_MouseDown(object sender, MouseEventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.Control;
isMouseDown = true;
}
private void bunifuImageButton1_MouseUp(object sender, MouseEventArgs e)
{
bunifuImageButton1.BackColor = SystemColors.HotTrack;
isMouseDown = false;
}
private void bunifuImageButton1_MouseMove(object sender, MouseEventArgs e)
{
// If the mouse is down and the mouse is not over the button
if (isMouseDown && !bunifuImageButton1.Bounds.Contains(e.Location))
{
bunifuImageButton1.BackColor = SystemColors.Highlight;
}
}
答案 1 :(得分:0)
您可以尝试使用平面样式按钮设置flatappearence颜色,并查看它是如何自动完成的。