我想在我的表单上显示一张图片,加载后一定秒数,然后让图片在表单边界内以受控方式移动。我很感激一个代码示例,它将让我开始定时事件。
public partial class Form1 : Form
{
int horiz, vert, step;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick_1(object sender, EventArgs e)
{
//image is moved at each interval of the timer
goblin.Left = goblin.Left + (horiz * step);
goblin.Top = goblin.Top + (vert * step);
// if goblin has hit the RHS edge, if so change direction left
if ((goblin.Left + goblin.Width) >= (Form1.ActiveForm.Width - step))
horiz = -1;
// if goblin has hit the LHS edge, if so change direction right
if (goblin.Left <= step)
horiz = 1;
// if goblin has hit the bottom edge, if so change direction upwards
if ((goblin.Top + goblin.Height) >= (Form1.ActiveForm.Height - step))
vert = -1;
// if goblin has hit the top edge, if so change direction downwards
if (goblin.Top < step)
vert = 1;
}
private void Form1_Load_1(object sender, EventArgs e)
{
//Soon as the forms loads activate the goblin to start moving
//set the intial direction
horiz = 1; //start going right
vert = 1; //start going down
step = 5; //moves goblin 5 pixels
timer1.Enabled = true;
}
}
}
答案 0 :(得分:1)
基于您迄今为止向我们展示的最简单的解决方案是使用您已经使用的相同计时器,并且基本上跳过几个滴答。我们假设您当前的计时器发生在100ms
,即每秒10个定时器(10hz)
如果您想将此活动延迟5秒,则需要跳过第一个刻度的5 * 10
(50)。创建一个新的整数成员变量来存储您已处理的滴答数:
private int ticks = 0;
每次计时器到期/滴答时首先执行此操作:
ticks++;
if (ticks < 50) {
// Don't do anything just skip
return;
}
答案 1 :(得分:1)
您可以提供第二个“临时”计时器(timer2)
private void Form1_Load_1(object sender, EventArgs e)
{
//Soon as the forms loads activate the goblin to start moving
//set the intial direction
horiz = 1; //start going right
vert = 1; //start going down
step = 5; //moves goblin 5 pixels
timer1.Tick += timer1_Tick_1;
// temporary timer
Timer timer2 = new Timer();
timer2.Interval = 5000;
timer2.Tick += delegate
{
// activate goblin timer
timer1.Enabled = true;
// deactivate 5s temp timer
timer2.Enabled = false;
timer2.Dispose();
};
timer2.Enabled = true;
}