0

我正在创建一个带有两个图片框的应用程序,其中图像从数组加载并在每个计时器滴答时随机更改。我面临有时不加载图像的问题,使图片框带有一点红十字。我读到我应该在加载新图像之前处理上一个图像(我是 C# 新手),但是如果不让应用程序在第一次滴答时崩溃,我就无法让它工作。你能帮帮我吗?

private void timer_Tick(object sender, EventArgs e)
    {
        index1 = rand.Next(0, pics.Length - 1);
        index2 = rand.Next(0, pics.Length - 1);
        pcb1.ImageLocation = pics[index1];
        pcb2.ImageLocation = pics[index2];
    }



try
{
    pcb1.Image.Dispose();
    pcb2.Image.Dispose();
    index1 = rand.Next(0, pics.Length - 1);
    index2 = rand.Next(0, pics.Length - 1);
    pcb1.ImageLocation = pics[index1];
    pcb2.ImageLocation = pics[index2];
}
catch (Exception)
{ 
    throw; 
}

- 告诉我 System.ArgumentException

4

1 回答 1

0

一个可能的解决方案:

try
{
    private void timer_Tick(object sender, EventArgs e)
    {
        index1 = rand.Next(0, pics.Length);
        if (File.Exists(pics[index1]))
        {
            Image img1 = Image.FromFile(pics[index1]);
            pcb1.Image = img1;
        }
        index2 = rand.Next(0, pics.Length);
        if (File.Exists(pics[index2]))
        {
            Image img2 = Image.FromFile(pics[index2]);
            pcb2.Image = img2;
        }
    }
}
catch (OutOfMemoryException oomEx)
{
    MessageBox.Show("Not a valid image.");
}
catch (Exception ex)
{
    //all others...respond appropriately
}
于 2013-05-30T15:58:33.727 回答