现在的位置: 首页 > 综合 > 正文

使 TextBox1 的 UI 可以更新

2012年02月09日 ⁄ 综合 ⁄ 共 1769字 ⁄ 字号 评论关闭

Timer timer1;
int curNum;
System.Threading.Thread thread;

/// <summary>
/// 自动增加 (使 TextBox1 的 UI 可以更新)
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i <= 1000; i++)
    {
        this.textBox1.Text = i.ToString();
        this.Refresh(); //刷新控件
        Application.DoEvents(); //延时20毫秒, 一般情况下跟上面的语句一起使用
    }
}

/// <summary>
/// 时钟自动增加
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button2_Click(object sender, EventArgs e)
{
    curNum = 0;
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);  //增加一个timer1.Tick事件
    timer1.Interval = 1000;  //时间间隔,默认为毫秒 (到了这个时间就执行一个Tick事件)
    timer1.Enabled = true;  //设置计时器在运行
    timer1.Start();  //启动计时器
}
private void timer1_Tick(object sender, EventArgs e)
{
    if (curNum < 10)
    {
        curNum = curNum + 1;
        this.textBox1.Text = curNum.ToString();
    }
    else
    {
        timer1.Enabled = false;  //设置计时器不在运行
        timer1.Stop();  //停止计时器
        MessageBox.Show("计时结束", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

/// <summary>
/// 线程自动增加
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button3_Click(object sender, EventArgs e)
{
    //如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态
    Control.CheckForIllegalCrossThreadCalls = false;  //访问控件的方法或属性之一的线程是不是创建该控件的线程(本例中为FALSE表示不是创建textBox1的线程也可以访问它)
    thread = new System.Threading.Thread(AutoAddNumber);           
    thread.Start();
}
private void AutoAddNumber()
{
    for (int i = 0; i <= 1000; i++)
    {
        this.textBox1.Text = i.ToString();
    }           
}

抱歉!评论已关闭.