C#线程中更改TextBox 和RichText的值

来源:互联网 发布:python中异常处理 编辑:程序博客网 时间:2024/06/07 23:00

C#线程中更改TextBox 和RichText的值

        delegate void SetTextCallback(string text);        private void SetText(string text)        {            if (this.txtLog.InvokeRequired)            {                SetTextCallback d = new SetTextCallback(SetText);                this.Invoke(d, new object[] { text });            }            else            {                txtLog.AppendText(text + Environment.NewLine);                txtLog.ScrollToCaret();                this.txtLog.Focus();                this.txtLog.Select(this.txtLog.TextLength, 0);                this.txtLog.ScrollToCaret();            }        }
RichText可以设置字体、字体颜色、背景色等信息

private bool m_bolHighlight = false;        private delegate void delInfoList(string text);//申明委托,防止不同线程设置richtextbox时出现错误        void SetrichTextBox(string value)        {            if (rtxtLogs.InvokeRequired)            {                delInfoList d = new delInfoList(SetrichTextBox);                rtxtLogs.Invoke(d, value);            }            else            {                if (rtxtLogs.Lines.Length > 5000)                {                    rtxtLogs.Clear();                                    }                //========richtextbox滚动条自动移至最后一条记录                //让文本框获取焦点                  rtxtLogs.Focus();                //设置光标的位置到文本尾                  rtxtLogs.Select(rtxtLogs.TextLength, 0);                //滚动到控件光标处                  rtxtLogs.ScrollToCaret();                if (m_bolHighlight)                {                    rtxtLogs.SelectionFont = new Font("Verdana", 9, FontStyle.Bold);                    rtxtLogs.SelectionColor = Color.Red;                }                rtxtLogs.AppendText(value + Environment.NewLine);                            }        }