我有一个只读的数据记录窗口,使用RichTextBox控件实现。我希望能够禁用当用户点击控件时发生的自动滚动,以便用户可以选择特定的日志进行复制/粘贴操作或其他操作。但是,一旦用户在RichTextBox中单击,它会自动滚动到底部,这使得操作变得困难。
有人知道如何覆盖此行为吗?
谢谢!
我有一个只读的数据记录窗口,使用RichTextBox控件实现。我希望能够禁用当用户点击控件时发生的自动滚动,以便用户可以选择特定的日志进行复制/粘贴操作或其他操作。但是,一旦用户在RichTextBox中单击,它会自动滚动到底部,这使得操作变得困难。
有人知道如何覆盖此行为吗?
谢谢!
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
const int WM_USER = 0x400;
const int EM_HIDESELECTION = WM_USER + 63;
void OnAppend(string text)
{
bool focused = richTextBox1.Focused;
//backup initial selection
int selection = richTextBox1.SelectionStart;
int length = richTextBox1.SelectionLength;
//allow autoscroll if selection is at end of text
bool autoscroll = (selection==richTextBox1.Text.Length);
if (!autoscroll)
{
//shift focus from RichTextBox to some other control
if (focused) textBox1.Focus();
//hide selection
SendMessage(richTextBox1.Handle, EM_HIDESELECTION, 1, 0);
}
richTextBox1.AppendText(text);
if (!autoscroll)
{
//restore initial selection
richTextBox1.SelectionStart = selection;
richTextBox1.SelectionLength = length;
//unhide selection
SendMessage(richTextBox1.Handle, EM_HIDESELECTION, 0, 0);
//restore focus to RichTextBox
if(focused) richTextBox1.Focus();
}
}
你可以尝试以下方法:
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LockWindowUpdate(IntPtr Handle);
然后在你追加日志数据的方法中(我做了一些假设),你可以这样做:
LockWindowUpdate(this.Handle);
int pos = richTextBox1.SelectionStart;
int len = richTextBox1.SelectionLength;
richTextBox1.AppendText(yourText);
richTextBox1.SelectionStart = pos;
richTextBox1.SelectionLength = len;
LockWindowUpdate(IntPtr.Zero);
我做了一个小测试应用程序,其中包含一个计时器,它在richtextbox上进行附加,并停止了滚动,以便我可以进行文本选择。它有一些位置问题,不是完美的,但也许它会帮助你朝着自己的解决方案迈进。
祝一切顺利!
[System.Runtime.InteropServices.DllImport("User32.dll")]
extern static int GetScrollPos(IntPtr hWnd, int nBar);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
这个解决方案对我来说更加完整。