• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
永不言弃,简单就好
每一个付出,都有回报,永远不放弃
博客园    首页    新随笔    联系   管理    订阅  订阅
使 TextBox1 的 UI 可以更新

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();
    }           
}

posted on 2008-11-24 23:37  嘎子  阅读(321)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3