Reputation: 370
I'm coding a .Net application using Windows.Forms in C#. I am making a scoreboard imitation using pictureboxes. The plan is to amount their width 2px every timer tick until they reach desired width. And that's the problem, because I have no idea how to tell the timer tick function what picturebox's width it should increment. I don't want to use a different method for every picturebox, because I don't think it's really the optimal way to do it.
So, the question is, how can I set specified pixtureboxes and desired widths to be affected by timer_tick method?
I am trying to do something like the board in the Polish version of Family Feud: https://www.youtube.com/watch?v=uL-y18ZkbcQ (watch from 3:05)
Upvotes: 1
Views: 544
Reputation: 941625
Just write a little helper class to keep track of the timer and the picture box. It could look like this:
class Animator : IDisposable {
private Timer timer;
private PictureBox pbox;
private int maxSize;
public Animator(PictureBox box, int size) {
pbox = box;
maxSize = size;
timer = new Timer() { Interval = 45, Enabled = true };
timer.Tick += animate;
}
private void animate(object sender, EventArgs e) {
if (pbox.IsDisposed || pbox.Width >= maxSize) Dispose();
else pbox.Width += Math.Min(2, maxSize - pbox.Width);
}
public void Dispose() { timer.Dispose(); }
}
Now you can create as many as you want with a simple statement in your Form class:
new Animator(pictureBox1, 50);
Upvotes: 4