ThreadSafe CaretIndex- WinForm

时间:2018-11-25 20:15:08

标签: c#

我有一个多行文本框,使用threadsafe方法来调用它。 每输入一个新文本后,插入符号(光标)将移至第一行,多行文本也将移至该位置。我看不懂最后几行。

我尝试使用:

 textBox.CaretIndex = _textBox.Text.Length;

但不适用于threadsafe

这是我的代码:

void test()
{
Thread demoThread =
               new Thread(new ThreadStart(this.ThreadProcSafe));
            demoThread.Start();
}
private void ThreadProcSafe()
{
    ThreadHelperClass.SetText(this, textBox2, "text: ");
}
public static class ThreadHelperClass{
    delegate void SetTextCallback(Form f, Control ctrl, string text);
    /// <summary>
    /// Set text property of various controls
    /// </summary>
    /// <param name="form">The calling form</param>
    /// <param name="ctrl"></param>
    /// <param name="text"></param>
    public static void SetText(Form form, Control ctrl, string text){
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (ctrl.InvokeRequired){
            SetTextCallback d = new SetTextCallback(SetText);
            form.Invoke(d, new object[] { form, ctrl, text });
        } else {
            ctrl.Text += text;
            ctrl.Text += Environment.NewLine;
        }
    }
}

ThreadHelperClass.SetText(this, richTextBox1, "output>>" + e.Data);

我想在文本框的末尾(有关最后一行文本),而无需单击或移动鼠标。输入新文本后,插入符号转到行尾。

我想在ThreadHelperClass上使用Setting cursor at the end of any text of a textbox,但它给我错误

想要使用

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;
OR
txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;
OR
txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

这是我在ThreadHelperClass中使用以上代码时遇到的错误 严重性代码说明项目文件行抑制状态 错误CS0120非静态字段,方法或属性'Form1.textBox2'需要对象引用。下载C:\ Users \ work \ source \ repos \ Download \ Download \ Form1.cs 108活动

当我在此功能之外使用它时,我的应用程序因多线程而崩溃

2 个答案:

答案 0 :(得分:0)

您可以尝试从GUI线程调用textBox.CaretIndex = _textBox.Text.Length;吗?

Application.Current.Dispatcher.Invoke(
    () =>
    {
         textBox.CaretIndex = _textBox.Text.Length;
    });

答案 1 :(得分:0)

使用解决的问题 Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

<properties>
    <sonar.skip>true</sonar.skip>
</properties>

通过这种方式,我可以使用文本框和所有子命令,例如“焦点”,“跨线程操作中的选择”而不会崩溃。

delegate void SetTextCallback(string text);

private void SetText(string text)
{
  // InvokeRequired required compares the thread ID of the
  // calling thread to the thread ID of the creating thread.
  // If these threads are different, it returns true.
  if (this.textBox1.InvokeRequired)
  { 
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
  }
  else
  {
    this.textBox1.Text = text;
  }
}

但是在我的问题代码中有一个

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);
没有选择,聚焦的

我也想知道旧方法的答案

无论如何谢谢

相关问题