2014-10-18 68 views
0

我迷惑在这其中,Windows窗体称为“联系”有时“欢迎屏幕”之后叫了两声,有时(“联系方式”)被调用一次只要。我非常肯定,我只称一次表格。的WinForms有时会出现两次,有时一次

这里是我使用的代码:

下面的 “WelcomeScreen” 的形式是运行程序时调用的第一个:

public partial class WelcomeScreen : Form 
    { 
     int timeLeft = 5; 

     Timer _timer = new Timer(); 

     BackgroundWorker _backgroundWorker = new BackgroundWorker(); 

     public WelcomeScreen() 
     { 
      InitializeComponent(); 

      _backgroundWorker.WorkerReportsProgress = true; 

      _backgroundWorker.DoWork += BackgroundWorker_DoWork; 

      _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; 

      _timer.Interval = 1000; 

      _timer.Tick += Timer_Tick; 
     } 

     void WelcomeScreen_Load(object sender, EventArgs e) 
     { 
      _backgroundWorker.RunWorkerAsync(); 
     } 

     void Timer_Tick(object sender, EventArgs e) 
     { 
      timeLeft--; 

      if (timeLeft <= 0) 
      { 
       _timer.Stop(); 

       this.Hide(); 

       Contact _contact = new Contact(); 

       _contact.ShowDialog(); 

       this.Close(); 
      } 
     } 

     void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
     { 
      progressBar1.Value = e.ProgressPercentage; 

      if (e.ProgressPercentage <= 300) 
      { 
       _timer.Start(); 

       this.label3.Text = "Completed (" + timeLeft + ") "; 
       this.label4.Text = string.Empty; 
      } 

     } 

     void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
     { 
      for (int i = 0; i <= 300; i++) 
      { 
       _backgroundWorker.ReportProgress(i); 

       System.Threading.Thread.Sleep(200); 
      } 
     } 

下面的表格“联系人“在”欢迎屏幕“之后调用:

public partial class Contact : Form 
    { 
     const int CP_NOCLOSE_BUTTON = 0x200; 

     public Contact() 
     { 
      InitializeComponent(); 
     } 

     void Contact_Load(object sender, EventArgs e) 
     { 
      SystemManager.SoundEffect(); 
     } 

     void button1_Click(object sender, EventArgs e) 
     { 
      this.Hide(); 

      Loading _loading = new Loading(); 

      _loading.ShowDialog(); 

      this.Close(); 
     } 

     protected override CreateParams CreateParams 
     { 
      get 
      { 
       CreateParams myCp = base.CreateParams; 
       myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON; 
       return myCp; 
      } 
     } 

我很感谢你的回答!

谢谢

+2

在代码中使用断点并检查调用次数。如果是两次检查Callstack并查看原因! – mybirthname 2014-10-18 06:08:09

+0

你也可以检查表格是否已经打开或没有,如果它已经打开don'call它。使用'WindowState' – 2014-10-18 06:13:10

+0

我想'WindowState'是最大化,最小化和正常的正确的先生@VijaySinghRana。 – 2014-10-18 06:28:14

回答

0

它看起来像你的Timer造成问题,通过发射多次...

你有你的计时器代码中这个条件:

if (timeLeft <= 0) 

而行之前是timeLeft--。在timeLeft变为0之后,它将继续变小(-1,-2等),并且每次都会显示表单。

快速解决方法是将条件更改为timeLeft == 0或将timeLeft的类型更改为uint。当然,这些都是黑客。正确的解决办法是修复你的代码,在需要时停止定时器发射。

+1

谢谢。它确实解决了我的问题 – 2014-10-18 06:27:40

相关问题