Reputation: 618
Can someone help about create a winform animation like in Win7 Calculator when you hover mouse over button, currently i use bunch of image then looping it in backgroundworker, but i think its wrong, this is my code:
this occur when mouse enter,
private void bgTurnOn_DoWork(object sender, DoWorkEventArgs e)
{
Label labelSender = (Label)e.Argument;
int ii = labelSender.ImageIndex;
for (int i = ii + 4; i <= 11; i++)
{
if (labelSender.AllowDrop)
{
labelSender.ImageIndex = i;
Thread.Sleep(40);
}
}
}
and this when mouse leave
private void bgTurnOff_DoWork(object sender, DoWorkEventArgs e)
{
Label labelSender = (Label)e.Argument;
int ii = labelSender.ImageIndex;
for (int i = ii; i >= 0; i--)
{
if (!labelSender.AllowDrop)
{
labelSender.ImageIndex = i;
Thread.Sleep(80);
}
}
}
note: I just use AllowDrop so I do not bother to declare new variable, i have 42 button, so i think i need more efficient solution.
Upvotes: 1
Views: 1343
Reputation: 14522
It seems that you want a glow effect, so you can use the next idea:
OpacityPictureBox : PictureBox
which supports opacity (in levels of 1-100 or double 0-1). See this for more information.MaxOpacity
and MinOpacity
to the OpacityPictureBox
class, for easy and safe range checks from the outside. The values might be 0, 100 or 0, 1, or something else, depending on your implementation of opacity.AnimatedPictureBox : UserControl
which holds 1 PictureBox
named pbNormal
and 1 OpacityPictureBox
named opbHover
, both Dock = DockStyle.Fill
, and one timer named timer
. Make sure that pbNormal
is below opbHover
.Normal
of type Image
which delegates into pbNormal.Image
Hover
of type Image
which delegates into opbHover.Image
AnimationInterval
of type int
which delgates into timer.Interval
AnimatedPictureBox
, after calling InitializeComponents
, do opbHover.Opacity = 0;
. You can also do this.Cursor = Cursors.Hand;
if you want the cursor to change into a hand when hovering over it._animationDirection
of type int
, which will be -1 or 1.Code:
private void Animate(int animationDirection)
{
this._animationDirection = animationDirection;
this.timer.Start();
}
OnMouseEnter
and OnMouseLeave
:Code:
protected override void OnMouseEnter(EventArgs e)
{
this.Animate(1);
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
this.Animate(-1);
base.OnMouseEnter(e);
}
timer.Tick
event and with this:Code:
private void timer_Tick(object sender, EventArgs e)
{
var hoverOpacity = this.opbHover.Opacity + this._animationDirection;
if (hoverOpacity < OpacityPictureBox.MinOpacity ||
hoverOpacity > OpacityPictureBox.MaxOpacity)
{
this.timer.Stop();
return;
}
this.opbHover.Opacity = hoverOpacity;
}
Upvotes: 1