Reputation:
I'm trying to move image on the panel with timer.tick but it doesn't work for some reason... Timer is enabled in properties window and this is my code:
public partial class Form1 : Form
{
private Image img;
private Point pos;
public Form1()
{
InitializeComponent();
img = Image.FromFile("C:/object.png");
pos = new Point(100, 100);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, pos);
}
private void timer1_Tick(object sender, EventArgs e)
{
pos.X += 10;
pos.Y += 10;
Invalidate();
}
}
I can't see what is the problem here?? :)
I also tried this:
public partial class Form1 : Form
{
private Image img;
private Point pos;
public Form1()
{
InitializeComponent();
img = Image.FromFile("C:/object.png");
pos = new Point(100, 100);
Timer myTimer = new Timer();
myTimer.Enabled = true; // don't know if this goes here
myTimer.Tick += new EventHandler(MoveImg);
myTimer.Interval = 100;
myTimer.Start();
}
private void MoveImg(Object myObject, EventArgs myEventArgs)
{
pos.X += 10;
pos.Y += 10;
Invalidate();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(img, pos);
}
}
Upvotes: 0
Views: 104
Reputation: 5488
You need to start the timer using Timer.Start()
public Form1()
{
InitializeComponent();
img = Image.FromFile("C:/object.png");
pos = new Point(100, 100);
timer1.Start();
}
And as Hans Passant says - you have to Invalidate the right object.
private void MoveImg(Object myObject, EventArgs myEventArgs)
{
pos.X += 10;
pos.Y += 10;
panel1.Invalidate();
}
Upvotes: 2