Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.3k views
in Technique[技术] by (71.8m points)

c# - Stop and start gif animation in PictureBox by enabling and disabling it in mouse events

I added a gif to a PictureBox and when the form is loaded I disabled the PictureBox to stop playing the gif. Then when I hover cursor on PictureBox I would like to enable the PictureBox to start playing the gif, but it doesn't play the gif.

Why I cannot enable the PictureBox and play the gif on mouse hover and how can I solve this problem?

code:

private void MainPage_Load(object sender, EventArgs e)
{
    pictureBox1.Enabled = false;
}

private void pictureBox1_MouseHover(object sender, EventArgs e)
{
    pictureBox1.Enabled = true;  
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    pictureBox1.Enabled = false;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Receiving Mouse events for a disabled control

When a control is disabled, mouse events will not be received by the control, instead they will be received by its parent.

So in this case you can handle MouseHover event of the parent and see if the mouse position is inside the bound of the PictureBox, then enable it.

For example. assuming the parent of the picture box is the form:

private void form1_MouseHover(object sender, EventArgs e)
{
    if (pictureBox1.Bounds.Contains(this.PointToClient(Cursor.Position)))
    {
        pictureBox1.Enabled = true;
    }
}

Stop or start gif animation in PictureBox

In addition to disabling and enabling PictureBox to start or stop gif animation, another option for enabling or disabling the animation by invoking the private void Animate(bool animate) method:

void Animate(PictureBox pictureBox, bool animate)
{
    var animateMethod = typeof(PictureBox).GetMethod("Animate",
    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
    null, new Type[] { typeof(bool) }, null);
    animateMethod.Invoke(pictureBox, new object[] { animate });
}

Then without disabling the control:

Animate(pictureBox1, true); //Start animation
Animate(pictureBox1, false); //Stop animation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...