WinForms有时出现两次,有时出现一次
本文关键字:一次 WinForms 两次 | 更新日期: 2023-09-27 18:26:54
我对此感到困惑,名为"联系人"的windows窗体有时在《欢迎屏幕》之后调用两次,有时它("联系人")只调用一次。我确信我只调用过一次表单。
这是我正在使用的代码:
"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;
}
}
我很感激你的回答!
感谢
似乎是您的Timer
通过多次激发。。。
你的计时器代码中有这种情况:
if (timeLeft <= 0)
前面的行是timeLeft--
。timeLeft
变为0后,它将继续变小(-1、-2等),并且每次都会显示表单。
快速解决方法是将条件更改为timeLeft == 0
或将timeLeft
的类型更改为uint
。当然,这两个都是技巧。正确的修复方法是修复代码,以在需要时阻止计时器启动。