Reputation: 15
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;
}
Upvotes: 1
Views: 1436
Reputation: 125197
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
Upvotes: 2