gpt4 book ai didi

c# - ThreadSafe CaretIndex-WinForm

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:40 27 4
gpt4 key购买 nike

我有一个多行文本框,它使用 threadsafe 方法来调用它。在每个新文本之后,插入符号(光标)转到第一行位置和多行文本。我无法阅读最后几行。

我尝试使用:

 textBox.CaretIndex = _textBox.Text.Length;

但它不适用于线程安全

这是我的代码:

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

我想在不单击或移动鼠标的情况下转到文本框的末尾(查看最后一行文本)。在新文本之后,插入符号转到行尾。

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

想用

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 Active

当我在这个函数之外使用它时,我的应用程序会因多线程而崩溃

最佳答案

你能尝试从 GUI 线程调用 textBox.CaretIndex = _textBox.Text.Length; 吗?

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

关于c# - ThreadSafe CaretIndex-WinForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53471502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com