以定时间隔创建和显示表单

时间:2013-07-21 22:24:16

标签: c# winforms

我正在尝试以定时间隔创建和显示某些表单。表单包含一个图片框并显示动画gif。在每个间隔,关闭先前的gif,并创建和显示新的gif。我能够将这个用于单个表单/ GIF,但如果我尝试一次显示多个表单,我会遇到问题。

以下是我尝试过的结构:

private void m_intervalCountDown_OnCountDownCompleted(object sender, EventArgs e)
{
   //the timed event has fired       

   PrepareAndDisplayNextForms();

}

private void PrepareAndDisplayNextForms()
{
   ClosePreviousForms();

   //I loop through a list of gifs and call:
   System.Drawing.Image img = System.Drawing.Image.FromFile(m_filePath);
   Form_Gif formGif = new Form_Gif(img);

   //I then add each Form_Gif to a previously created ConcurentDictionary      

   DisplayGifs();

}

private void ClosePreviousForms()
{
   //I loop through a list containing the forms, and i call:
   myForm.Close();
   myForm.picturebox.dispose();
   myForm.dispose();

   //It turns out that I have to use an Invoke on the form here to close it, even
   //though I haven't explicitly created a new thread/task, but I assume that when the
   //timed event fires a new thread is created internally or something.


   //i'm not great at figuring out when calling dispose is necessary, but i think that
   //because I loaded an image into the picturebox that I should dispose of it,
   //although i'm not certain.  I'm even less certain about whether dispose on the form
   //is required, but I figured it wouldn't hurt much.
}



private void DisplayGifs()
{
   //I loop through my list of Form_Gif's and try to .Show() them
   //Here is where the problem manifests itself.

   //If I use:
   myFormGif.Show();

   //then the form doesn't become visible, but if you move the mouse cursor
   //over the spot where the form should be, the cursor changes to the "wait" animation


   //If I use:
   myFormGif.ShowDialog();

   //this will display one form at a time, but I can't show multiple forms at once.
   //I thought that it might be because i am using the same thread to ShowDialog on 
   //each of the forms, and the ShowDialog of the first form prevents the next one from
   //being called.


   //So then I tried:

   Task t = null;
   CancellationTokenSource searchTokenSource = new CancellationTokenSource();

   t = Task.Factory.StartNew(() => myFormGif.ShowDialog(), searchTokenSource.Token);


   //but again while this works for individual gifForms, I can't show more than one at
   //a time; if I try, i get an InvalidOperationException:  "Form that is already
   // displayed modally cannot be displayed as a modal dialog box. Close the form
   // before calling showDialog."

}

我的想法是,如果定时事件允许我使用主线程显示表单,我可以调用.Show(),一切都会成功。当我测试在buttonclick事件上显示多个表单时,使用.Show()计算得很好。但是当我引入System.Timer事件时,.Show()并没有成功。

0 个答案:

没有答案