[英]C# Preventing RichTextBox from scrolling/jumping to top
看來,當使用System.Windows.Forms.RichTextBox
您可以使用textbox.AppendText()
或textbox.Text = ""
將文本添加到文本框中。
AppendText
將滾動到底部,直接添加文本將不會滾動,但是當用戶將文本框聚焦時,它將跳轉到頂部。
這是我的功能:
// Function to add a line to the textbox that gets called each time I want to add something
// console = textbox
public void addLine(String line)
{
// Invoking since this function gets accessed by another thread
console.Invoke((MethodInvoker)delegate
{
// Check if user wants the textbox to scroll
if (Settings.Default.enableScrolling)
{
// Only normal inserting into textbox here with AppendText()
}
else
{
// This is the part that doesn't work
// When adding text directly like this the textbox will jump to the top if the textbox is focused, which is pretty annoying
Console.WriteLine(line);
console.Text += "\r\n" + line;
}
});
}
我也嘗試導入user32.dll
並覆蓋滾動功能,這些功能效果不佳。
有誰知道如何一勞永逸地停止滾動文本框?
它不應該是頂部,也不應該到底部,當然也不應該是當前的選擇,而是保持目前的狀態。
console.Text += "\r\n" + line;
這不符合你的想法。 它是一個賦值 ,它完全取代了Text屬性。 + =運算符是方便的語法糖,但執行的實際代碼是
console.Text = console.Text + "\r\n" + line;
RichTextBox不會將舊文本與新文本進行比較,以尋找可能將插入位置保持在同一位置的可能匹配。 因此它將插入符號移回文本中的第一行。 這反過來導致它向后滾動。 跳。
你肯定想避免這種代碼,它非常昂貴。 如果您努力格式化文本並且不愉快,您將失去格式。 而是支持AppendText()方法追加文本和SelectionText屬性來插入文本(在更改SelectionStart屬性之后)。 不僅有速度而且沒有滾動的好處。
在這之后:
Console.WriteLine(line);
console.Text += "\r\n" + line;
只需添加以下兩行:
console.Select(console.Text.Length-1, 1);
console.ScrollToCaret();
快樂的編碼
然后,如果我找到你,你應該試試這個:
Console.WriteLine(line);
console.SelectionProtected = true;
console.Text += "\r\n" + line;
當我嘗試它時,它的工作方式就像你想要的那樣。
我必須實現類似的東西,所以我想分享......
什么時候:
我接受了Hans Passant關於使用AppendText()和SelectionStart屬性的建議。 以下是我的代碼的樣子:
int caretPosition = myTextBox.SelectionStart;
myTextBox.AppendText("The text being appended \r\n");
if (myTextBox.Focused)
{
myTextBox.Select(caretPosition, 0);
myTextBox.ScrollToCaret();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.