Liny_@NotePad

沉迷ACG中

WinForm试用ing = =。。ProgressBar

YOYO posted @ 2010年8月04日 20:00 in 【C#】 with tags WinForm , 2627 阅读

.NET 2.0开始不能跨线程访问控件,只能写委托,恨……

那么下面贴一段跨线程调度进度条的代码,无知的我搞了老半天……

首先,进度条叫做pbar_importState,用户输入控件全放在groupBox里,单击按钮开始执行某事件(通过副线程执行),同时开始播放进度条(通过副线程2),在事件完成后不再显示进度条。。播放期间,进度条如果到头了就重新开始播放。。

        # region 委托

        /// <summary>
        /// 设置控件是否可用
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isEnable"></param>
        private delegate void SetEnable(Control control, bool isEnable);

        /// <summary>
        /// 设置控件是否可见
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isVisible"></param>
        private delegate void SetVisible(Control control, bool isVisible);

        /// <summary>
        /// 进程条运行
        /// </summary>
        /// <param name="pbar"></param>
        private delegate void ProgressRun(ProgressBar pbar);

        # endregion
        /// <summary>
        /// 设置控件可用
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isEnable"></param>
        private void SetObjectEnable(Control control, bool isEnable)
        {
            control.Enabled = isEnable;
            this.Refresh();
        }

        /// <summary>
        /// 设置控件可见
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isVisible"></param>
        private void SetObjectVisible(Control control, bool isVisible)
        {
            control.Visible = isVisible;
            this.Refresh();
        }

        /// <summary>
        /// 进程条执行步
        /// </summary>
        /// <param name="pbar"></param>
        private void Progressing(ProgressBar pbar)
        {
            if (pbar.Value == pbar.Maximum)
            {
                pbar.Value = pbar.Minimum;
            }

            pbar.PerformStep();
        }

        /// <summary>
        /// 进度条运行
        /// </summary>
        private void RunProgress()
        {
            pbar_importState.Invoke(new SetVisible(SetObjectVisible), new object[] { pbar_importState, true });

            groupBox.Invoke(new SetEnable(SetObjectEnable), new object[] { groupBox, false });

            while (importThread.IsAlive)
            {
                pbar_importState.Invoke(new ProgressRun(Progressing), new object[] { pbar_importState });

                Thread.Sleep(10);
            }

            pbar_importState.Invoke(new SetVisible(SetObjectVisible), new object[] { pbar_importState, false });

            groupBox.Invoke(new SetEnable(SetObjectEnable), new object[] { groupBox, true });
        }

        #endregion
            new Thread(new ThreadStart(RunProgress)).Start();

            // 导入结构线程启动
            importThread.Start();

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter