当Form2.Show()时,如何强制Form2.label1.Text立即出现?

时间:2012-12-08 14:40:04

标签: c# forms label delay show

我有这段代码:

namespace TuyenTk
{
    public partial class Form1 : Form
    {
        Form2 _form2 = new Form2("");
        public Form1()
        {
            InitializeComponent();
            _form2.Show();
            int i = 0;
            while (i < 5)
            {
                _form2.label1.Text = "" + i;
                Thread.Sleep(500);
                i++;
            }
        }
    }

    public class Form2 : Form
    {
        public System.Windows.Forms.Label label1;
        public System.ComponentModel.Container components = null;

        public Form2()
        {
            InitializeComponent();
        }
        private void InitializeComponent(string t)
        {
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(5, 5);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(290, 100);
            this.label1.TabIndex = 0;
            this.label1.Text = t;
            // 
            // Form2
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(300, 100);
            this.ControlBox = false;
            this.Controls.Add(this.label1);
            this.Name = "Form2";
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.ShowInTaskbar = false;
            this.ResumeLayout(false);    
        }
    }
}

当Form1运行时,它显示Form2,但Form2.label1背景为白色,没有文本。
2.5秒后,Form2.label1.Text = 4.所以我没有出现0,1,2,3的值。我该怎么办呢?非常感谢你。

2 个答案:

答案 0 :(得分:3)

您想要做的事情(定期更新标签)是通过使用Timer组件实现的(您可以从ToolBox中拖动它并放置在您的表单上)。

public partial class Form1 : Form
{
   Form2 _form2 = new Form2("");
   Timer _timer;
   int _counter;

   public Form1()
   {
       InitializeComponent();          
       _form2.Show();

       if (components == null)
           components = new System.ComponentModel.Container();
       _timer = new Timer(components); // required for correct disposing

       _timer.Interval = 500;
       _timer.Tick += timer_Tick;
       _timer.Start();
   }

   private void timer_Tick(object sender, EventArgs e)
   {
       if (_counter < 5)
       {
          _form2.label1.Text = _counter.ToString();
          _counter++;
          return;
       }

       _timer.Stop();
   }

同样在其他表单上创建公共控件并不是一个好主意 - 如果你真的需要在form2上更新一些值,那么最好在Form2类中声明公共方法/属性,这将更新标签:

public partial class Form2 : Form
{
     public int Value
     {             
         set { label1.Text = value.ToString(); }
     }
}

还要考虑将计时器移动到Form2(让这个表单自行更新)。

答案 1 :(得分:0)

如果在UI线程中调用Thread.Sleep(500);,则GUI将不负责任。这就是为什么你让你的Fomr2.label1的背景变白。我建议你移动你的代码

while (i < 5)
{
   _form2.label1.Text = "" + i;
   Thread.Sleep(500);
   i++;
}

到另一个线程。你可以参考这个link来实现你的目标。