winform跨线程操作控件




winform跨线程操作控件,比如给文本框控件赋值 ;要操作什么控件就得在NormalSet方法中自己加类型判断


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GameCommon
{
    /// <summary>
    /// 公共类
    /// 创建人:长江股神
    /// 2015.10.10
    /// </summary>
    public class Common
    {
        #region 跨线程操作控件

        private delegate void setTexBox(Form winForm, Control control, string s);
        /// <summary>
        /// 跨线程控件赋值
        /// </summary>
        /// <param name="winForm"></param>
        /// <param name="control"></param>
        /// <param name="txt"></param>
        public static void ControlSetText(Form winForm, Control control, string txt)
        {
            if (control.InvokeRequired)//等待异步
            {
                setTexBox fc = new setTexBox(InvokeSet);
                winForm.Invoke(fc, new object[] { winForm, control, txt });
            }
            else
            {
                NormalSet(winForm, control, txt);
            }
        }
        /// <summary>
        /// 委托主线程赋值
        /// </summary>
        /// <param name="winForm"></param>
        /// <param name="control"></param>
        /// <param name="txt"></param>
        private static void InvokeSet(Form winForm, Control control, string txt)
        {
            NormalSet(winForm, control, txt);
        }
        /// <summary>
        /// 正常赋值
        /// </summary>
        /// <param name="winForm"></param>
        /// <param name="control"></param>
        /// <param name="txt"></param>
        private static void NormalSet(Form winForm, Control control, string txt)
        {
            //不同控件采用不同赋值方法
            if (control is RichTextBox)
            {
                ((RichTextBox)control).AppendText(txt);
            }
            else if (control is TextBox)
            {
                ((TextBox)control).Text = txt;
            } 
        }
        #endregion

    }
}


使用方法:


//使用
Common.ControlSetText(this, 控件名, "文本");







相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页