C# PictureBox没有';不出现
我有一个C# PictureBox没有';不出现,c#,winforms,picturebox,C#,Winforms,Picturebox,我有一个if语句,其中if语句是一个foreach,用于从字符串[]访问每个字符串 字符串是从文件读取的NPC的一些参数。第一个参数表示NPC类型,有两个:“战斗”和“教学”,最后一个string[]用于“教学”NPC的参数是“结束”,其余参数表示照片名称,我想将其加载到“对话”图片框中 我的测试文件如下所示: teach poza1 poza2 end 因此,我有两张照片要加载到对话框PictureBox中。我的想法是,我必须在foreach语句中暂停5秒钟,否则对话框PictureBox图
if
语句,其中if语句是一个foreach
,用于从字符串[]
访问每个字符串
字符串是从文件读取的NPC的一些参数。第一个参数表示NPC类型,有两个:“战斗”和“教学”,最后一个string[]
用于“教学”NPC的参数是“结束”,其余参数表示照片名称,我想将其加载到“对话”图片框中
我的测试文件如下所示:
teach
poza1
poza2
end
因此,我有两张照片要加载到对话框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
}
在调试时,我意识到如果我使用消息框
,该函数将加载这两张照片。另外,我确信参数将通过if语句
修复此错误似乎很容易,但我不知道如何操作。您可能需要为图片框发出PictureBox.Refresh和/或DoEvents命令,才能真正获得加载和显示图片的机会
MessageBox会自动执行DoEvents。。。这就是为什么它在调试期间工作。您现在所做的只是冻结UI。改用System.Windows.Forms.Timer
。将计时器从工具箱中拖到窗体上
然后创建计时器可以访问的一些字段,以存储您的图片和当前图片位置:
private List<string> pics = new List<string>();
private int currentPic = 0;
然后你必须告诉计时器显示下一张图片。增加计数器,必要时将其重置。这样的办法应该行得通。根据需要修改
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();
}
在调用Sleep之前,请调用Application.DoEvents()
,尽管这是不受欢迎的,而且通常不是正确的做法。从技术上讲,您需要执行一个对话框。调用并在委托过程中设置图像。@DanielA.White是的,这是在WinForms中,您正在加载图像,pb还没有时间显示它们。如果您想使用某种动画,计时器会更好,但是如果您在线程之前调用PB.Refresh.Sleep,它也应该可以工作。@RonBeyer如何在委托过程中设置图像类似于dialog.Invoke(委托{dialog.ImageLocation=…;})代码>谢谢,但它似乎也通过应用程序.DoEvents()
实现了。
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();
}