简体   繁体   English

在TextBox中更改滚动条位置?

[英]Change scrollbar position in TextBox?

If I want to change the position of a TextBox 's scrollbar, what do I need to do besides this: 如果我想更改TextBox滚动条的位置,除此之外我还需要做什么:

SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). 此函数仅更改滚动条位置,但它不会更新实际的TextBox (因此滚动条“滚动”,但文本不会)。 Any suggestions? 有什么建议么? I'm using Windows Forms and .NET 4, with Visual Studio 2008. 我在Visual Studio 2008中使用Windows Forms和.NET 4。

I usually do: 我经常这样做:

textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();

Where selecting 0 characters just moves the cursor to the desired location (in the example code: at the end of the text). 选择0个字符时,只需将光标移动到所需位置(在示例代码中:在文本末尾)。

First, define a constant value: 首先,定义一个常量值:

const int EM_LINESCROLL = 0x00B6;

Then, declare two external methods of user32.dll : 然后,声明user32.dll的两个外部方法:

[DllImport("user32.dll")]
static extern int SetScrollPos(IntPtr hWnd, int nBar, 
                               int nPos, bool bRedraw);
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int wMsg, 
                               int wParam, int lParam);

Finally, use these methods to do the real thing: 最后,使用这些方法来做真实的事情:

SetScrollPos(myTextBox.Handle,1,myTextBox.Lines.Length-1,true);
SendMessage(myTextBox.Handle,EM_LINESCROLL,0,
                             myTextBox.Lines.Length-1);

You may also use GetScrollPos() for scroll position saving when textbox is updated: 当文本框更新时,您还可以使用GetScrollPos()来保存滚动位置:

[DllImport("user32.dll")]
static extern int GetScrollPos(IntPtr hWnd, int nBar);

Do try to avoid controlling this directly, it just doesn't work really well. 尽量避免直接控制它,它只是不能很好地工作。 Set the TextBox.SelectionStart property to ensure the caret is the line you want to make visible. 设置TextBox.SelectionStart属性以确保插入符是要显示的行。 Then call ScrollToCaret. 然后调用ScrollToCaret。 The control must have the focus to make this work. 控件必须具有使其工作的重点。 Your user won't have any trouble finding it back. 您的用户在找回它时不会有任何问题。

TextBox is a wrapper for the grand-daddy of controls, it's 23 years old already, older than many SO users I reckon. TextBox是控件的祖父的包装器,它已经23岁了,比我认为的许多SO用户都要老。 Back when 640 KB was enough for everybody and Window 2.0 had to run on a 386SUX or less. 当640 KB对每个人都足够时,Window 2.0必须在386SUX或更低版本上运行。 The WPF version has more whistles. WPF版本有更多的口哨声。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM