图片框没有出现

PictureBox doesn't appear

我有一个 if 语句,里面的 if 语句是一个 foreach,用于从 string[] 访问每个 string

这些字符串是从文件中读取的 NPC 的一些参数。第一个代表 NPC 类型有两个:"battle" 和 "teach",最后一个 "teach" NPC 的 string[] 是 "end",其余参数表示照片名称,我想将其加载到 "dialog" PictureBox 中。

我的测试文件如下所示:

teach
poza1
poza2
end

所以我有 2 张照片要加载到对话框 PictureBox 中。这个想法是我必须暂停 foreach 语句 5 秒,否则对话框 PictureBox 图片加载速度太快,我将看不到它们。

所以我尝试这样做,代码如下所示:

if (date[0].Equals("teach")) //the first line of the date[] string, date represent the text from the file
{
    foreach (string parametru in date) // i think that you know what this does
    {
        if (parametru != "teach" && parametru != "end") // checking if the parameter isn't the first or the last line of the file
        {

            dialog.ImageLocation = folder + "/npc/" + score_npc + "/" + parametru + ".png"; //loading the photo
            System.Threading.Thread.Sleep(5000);

        }
    }
    //other instructions , irelevants in my opinion
}

在尝试调试时,我意识到如果我使用 MessageBox,该函数将加载两张照片。我也确信参数将通过 if 语句。

修复这个错误似乎很容易,但我不知道该怎么做。

您可能需要为图片框发出 PictureBox.Refresh and/or DoEvents 命令才能真正加载和显示图片。

MessageBox 自动执行 DoEvents ... 这就是它在调试期间工作的原因。

您现在所做的只是冻结 UI。请改用 System.Windows.Forms.Timer。将工具箱中的计时器拖放到您的表单上。

然后创建一些计时器可以访问的字段,用于存储您的照片和当前照片位置:

private List<string> pics = new List<string>();
private int currentPic = 0;

最后,载入你想要显示的图片,并启动 Timer 浏览它们:

pics.Clear();
pics.AddRange(date.Where(x => x != "teach" && x != "end"));
timer1.Interval = 5000;
timer1.Start();

然后你必须告诉你的定时器显示下一张图片。增加计数器,并在必要时重置它。这样的事情应该有效。根据需要修改。

private void timer1_Tick(object sender, EventArgs e)
{
    dialog.ImageLocation = string.Format("{0}/npc/{1}/{2}.png", folder, score_npc, pics[currentPic]);

    currentPic++;

    if (currentPic >= pics.Count)
        currentPic = 0;

    // Alternatively, stop the Timer when you get to the end, if you want
    // if (currentPic >= pics.Count)
    //     timer1.Stop();
}