【问题标题】:PictureBox doesn't appear图片框不出现
【发布时间】:2015-05-14 04:35:05
【问题描述】:

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

字符串是从文件中读取的 NPC 的一些参数。第一个代表NPC类型,有两个:“battle”和“teach”,“teach”NPC的最后一个string[]是“end”,其余参数代表我要加载的照片名称一个“对话框”图片框。

我的测试文件如下所示:

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 语句。

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

【问题讨论】:

  • 在致电 Sleep 之前,请致电 Application.DoEvents(),尽管这不受欢迎并且通常不是正确的做法。从技术上讲,您想做一个dialog.Invoke 并在委托过程中设置图像。
  • @DanielA.White 是的,这是在 winforms 中
  • 您在 pb 有时间显示它们之前加载图像。如果你想使用某种动画 Timer 会更好,但如果你在 thread.Sleep 之前调用 PB.Refresh 它应该也可以工作..
  • @RonBeyer 如何在委托过程中设置图像
  • 类似dialog.Invoke(delegate { dialog.ImageLocation = ...; });

标签: c# winforms picturebox


【解决方案1】:

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

然后创建一些 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();
}

【讨论】:

  • 谢谢,但看来Application.DoEvents() 也解决了。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-10-05
    • 2017-01-05
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多