WinForms有时会出现两次,有时会出现一次

时间:2014-10-18 06:04:15

标签: c# 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);
            }
        }

以下表格&#34;联系&#34;在&#34; WelcomeScreen&#34;:

之后调用
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;
            }
        }

感谢您的回答!

谢谢

1 个答案:

答案 0 :(得分:0)

看起来你的Timer导致了这个问题,多次点击......

您的计时器代码中包含以下条件:

if (timeLeft <= 0)

之前的行是timeLeft--timeLeft变为0后,它将继续变小(-1,-2等),每次都会显示该表格。

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