在Form2中没有显示图像

本文关键字:显示 显示图 图像 Form2 | 更新日期: 2023-09-27 18:08:51

我试图在特定时间段显示form2中的图像。列表框有10张图片(如下所示)。为什么在form2中没有显示图像?

list box is like
   1.C:''image1 ,2(sec),3(sec)  -----2sec-displaying the image1 ,3sec Displaying the blank image
   2.C:''image2 ,3(sec),1(sec)
   3.C:''image3 ,1(sec),2(sec)
     upto 10 image

Form1.cs

private void Showbtn_Click(object s, EventArgs e)
   {
     int i=0;
     while(i<listbox.items.count)
       {
          string strpath=listbox1.items[i].Tostring();
          string[] str1= strpth.Split(',');
          f2.updateimage(str1[0]);
          f2.show();
          System.Threading.Thread.Sleep((Convert.Toint32(str1[1]))*1000);
          String Blankimage=@"C://Blankimage.bmp";        
          f2.updateimage(Blankimage) ;
          f2.Show();
          System.Threading.thread.Sleep(Convert.Toint32(str1[2]) * 1000); 
          i++;
         }
    }   

Form2.cs

 public updateimage(string imgpath)
   {
       picturebox1.Load(imgpath);
    }
误差

  imageDisplay.exe' (Managed (v4.0.30319)): Loaded 'C:'Windows       'Microsoft.Net'assembly'GAC_32'mscorlib'v4.0_4.0.0.0__b77a5c561934e089'mscorlib.dll', Symbols loaded.
'imagedisplay.exe' (Managed (v4.0.30319)): Loaded 'C:'Windows'assembly'GAC_MSIL'Microsoft.VisualStudio.HostingProcess.Utilities'10.0.0.0__b03f5f7f11d50a3a'Microsoft.VisualStudio.HostingProcess.Utilities.dll', Symbols loaded.
   thread '<No name>' (0x02fc) has exited with code 0 

在Form2中没有显示图像

您必须让您的主UI在睡眠时更新表单(如刷新图像)。要做到这一点,你可以"异步等待",而不是用线程阻塞主线程。睡眠:

private async void Showbtn_Click(object s, EventArgs e)
{
    int i=0;
    while(i<listbox.items.count)
    {
        string strpath=listbox1.items[i].Tostring();
        string[] str1= strpth.Split(',');
        f2.updateimage(str1[0]);
        f2.show();
        await Task.Delay(Convert.Toint32(str1[1]));
        String Blankimage=@"C://Blankimage.bmp";        
        f2.updateimage(Blankimage) ;
        //f2.Show(); => You don't need that line
        await Task.Delay(Convert.Toint32(str1[2]));
        i++;
    }
} 

问题是主线程忙于while循环,所以我们要求它更新form2对象以再次绘制

public partial class Form1: Form{Form2 = new Form2();公共Form1 (){InitializeComponent ();}

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;
        f2.Show();
        while (i < listBox1.Items.Count)
        {
            string strpath = listBox1.Items[i].ToString();
            string[] str1 = strpath.Split(',');
            f2.updateimage(str1[0]);
            f2.Update();// Add This Line to make the second form update it self
            System.Threading.Thread.Sleep(5000);
            String Blankimage = @"C://Blankimage.bmp";     
            f2.updateimage(Blankimage);
            f2.Update(); // Add This Line to make the second form update it self
            System.Threading.Thread.Sleep(1000);
            i++;
        }
    }
}