我创建了一个Windows窗体,它有3个按钮。所以我想用一个按钮来改变使用mouseenter事件的颜色。这很好。但我需要通过淡入淡出或淡出来改变颜色。任何有这个问题答案的人请告诉我下面的代码我会告诉你我的mouseenter和mouseleave事件
private void button1_MouseEnter(object sender, EventArgs e)
{
button1.UseVisualStyleBackColor = false;
button1.BackColor = Color.Black;
button1.ForeColor = Color.White;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.UseVisualStyleBackColor = true;
button1.ForeColor = Color.Black;
}
答案 0 :(得分:0)
我为你写了一个小例子。它并不完美,但我认为它适用于你:)。
private void button1_MouseEnter(object sender, EventArgs e)
{
_colorCounter = 250;
button1.UseVisualStyleBackColor = false;
//button1.BackColor = Color.Black;
timer1.Start();
button1.ForeColor = Color.White;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
timer1.Stop();
_colorCounter = 250;
button1.UseVisualStyleBackColor = true;
button1.ForeColor = Color.Black;
button1.BackColor = SystemColors.Control;
}
private int _colorCounter = 250;
private void timer1_Tick(object sender, EventArgs e)
{
_colorCounter -= 25;
if (_colorCounter == 0)
{
timer1.Stop();
_colorCounter = 250;
}
else
{
// Build up a color from counter
button1.BackColor = Color.FromArgb(_colorCounter, _colorCounter, _colorCounter);
}
}
将n drop timer拖到表单中。
答案 1 :(得分:0)
这里有一些代码可以让你前进:它通过混合alpha通道引入一个新的颜色。
public Form1()
{
InitializeComponent();
oldColor = button1.BackColor;
}
Color oldColor;
Color newColor = Color.FromArgb(0, Color.MediumAquamarine); // your pick, including Black
int alpha = 0;
private void button1_MouseEnter(object sender, EventArgs e)
{
alpha = 0;
timer1.Interval = 15;
timer1.Start();
}
private void button1_MouseLeave(object sender, EventArgs e)
{
timer1.Stop();
button1.BackColor = oldColor;
button1.ForeColor = Color.Black;
}
private void timer1_Tick(object sender, EventArgs e)
{
alpha += 17; // change this for greater or less speed
button1.BackColor = Color.FromArgb(alpha, newColor);
if (alpha >= 255) timer1.Stop();
if (button1.BackColor.GetBrightness() < 0.3) button1.ForeColor = Color.White;
}
编辑:如果将newColor设置为太暗,则最后一个刻度线会将ForeColor设置为白色。
编辑2 :将相同的动画应用于多个按钮:
Button curButton;
MouseEnter
和MouseLeave
事件指向上面的相同事件MouseEnter
:Button curButton = (Button) sender;
button1
的每次出现更改为curButton
。为每个按钮
设置个别新颜色将newColors存储在Buttons&#39; Tags
而不是类变量:
button1.Tag = Color.MediumAquamarine;
button2.Tag = Color.MediumSeaGreen;
// ..等等.. 将其添加到MouseEnter
:newColor = (Color)curButton.Tag;
作为第二行
我开始喜欢整个事情,但不是黑色; - )