Messagebox将不会停止显示

本文关键字:显示 Messagebox | 更新日期: 2023-09-27 18:28:13

我正在尝试编写此代码,以便当单击从"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;
        }
    }
}

Messagebox将不会停止显示

//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();
}

获胜后尝试重新设置p.X。

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

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;
        }}}

点击按钮时,您应该调用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;
        }
    }
}

希望它能起作用。

您可以使用计时器。

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

您可以将它与tck事件关联起来。

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