我正在尝试使用timer.tick在面板上移动图像,但由于某种原因它不起作用... 在属性窗口中启用了计时器,这是我的代码:
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();
}
}
我看不出这里有什么问题? :)
我也试过这个:
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);
}
}
答案 0 :(得分:2)
您需要使用Timer.Start()
public Form1()
{
InitializeComponent();
img = Image.FromFile("C:/object.png");
pos = new Point(100, 100);
timer1.Start();
}
正如 Hans Passant 所说 - 你必须使正确的对象无效。
private void MoveImg(Object myObject, EventArgs myEventArgs)
{
pos.X += 10;
pos.Y += 10;
panel1.Invalidate();
}