Change scrollbar position in TextBox?

11,805

Solution 1

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

Solution 2

First, define a constant value:

const int EM_LINESCROLL = 0x00B6;

Then, declare two external methods of 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:

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

Solution 3

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. Then call 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. Back when 640 KB was enough for everybody and Window 2.0 had to run on a 386SUX or less. The WPF version has more whistles.

Share:
11,805
igal
Author by

igal

Updated on June 19, 2022

Comments

  • igal
    igal almost 2 years

    If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

    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). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

  • igal
    igal over 13 years
    what if i have 1 really long line like byte stream ?