Messagebox不会停止显示

时间:2013-08-19 07:23:30

标签: c# winforms

我正在尝试编写此代码,以便从"FORM1"点击启动Obj时将调用此方法并启用timer1

当我点击开始按钮时,狗图片将开始向右移动,直至到达X= 620,然后它会显示消息框" win"

然而,消息框一直显示,并且在dogpic到达目标线后不会停止

class dog
{
    public int startpost;
    public int TrackLenght = 620;
    public PictureBox dogpic = null;
    public int Location = 0;
    public Random random=new Random();

    public void ResetStart()
    { 
        dogpic.Location = new System.Drawing.Point(40, startpost);
    }

    public bool testrun()
    {
        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
            return false;
        }
        else
        {
            MessageBox.Show(dogpic.Name + " win");

            return true;
        }
    }
}

4 个答案:

答案 0 :(得分:3)

//suppose dog1 is an instance of your dog class
//here is the Tick event handler of your timer1
private void timer1_Tick(object sender, EventArgs e){
    timer1.Enable = !dog1.testrun();
}

答案 1 :(得分:1)

您可以使用计时器。

timer.Interval=5000;
timer.Enabled=true;
MessageBox.Show(dogpic.Name + " win");

您可以将其与tck事件相关联。

private void timer_Tick(object sender,EventArgs evt) {
    timer.Enabled=false;
}

答案 2 :(得分:1)

获胜后尝试重置pC。

不要看你的代码,但我认为你应该这样做:

public bool testrun()
    {

        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
           return false;
        }
        else
        {

            MessageBox.Show(dogpic.Name + " win");
            ResetStart()
            return true;
        }}}

答案 3 :(得分:1)

点击按钮,你应该调用ResetStart()函数,这将启用计时器并完成你的工作,并在到达终点时它应该禁用计时器。

class dog
{
    public int startpost;
    public int TrackLenght = 620;
    public PictureBox dogpic = null;
    public int Location = 0;
    public Random random=new Random();

    public void ResetStart()
    { 
        dogpic.Location = new System.Drawing.Point(40, startpost);
        timer.Enabled=true;
    }

    public bool testrun()
    {
        Point p = dogpic.Location;

        if (p.X < TrackLenght)
        {
            int distance = random.Next(5);

            p.X = p.X + distance;
            dogpic.Location = p;
            Location = dogpic.Location.X;
            return false;
        }
        else
        {
            MessageBox.Show(dogpic.Name + " win");
            timer.Enabled=false;    
            return true;
        }
    }
}

希望它能奏效。