Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll down in a textbox by code in C#

I am using winforms, and I update a text box once in a while (showing messages). however, when the text reaches the end of the box it produces scrollbars and I don't know how to scroll down to the bottom. The only thing I see is ScrollToCaret, but Caret is at the beginning of the text. What is the command to scroll?

like image 409
Nefzen Avatar asked Jul 01 '09 14:07

Nefzen


People also ask

How do you make a TextBox scrollable?

To change the properties of the text box, select the text box and then click Properties. The Properties sheet appears. You will want to change the EnterKeyBehavior, MultiLine and ScrollBars properties. Set the ScrollBar property to Both, Horizontal, Vertical etc according to your own needs.

How do I scroll a text box in C#?

// Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the ScrollBars property of the TextBox provided by the TextBox class.

What is TextBox control in C#?

Typically, a TextBox control is used to display, or accept as input, a single line of text. You can use the Multiline and ScrollBars properties to enable multiple lines of text to be displayed or entered.


2 Answers

You can do this by making use of a function called ScrollToCaret. You need to first set the caret position to the end of the text box, then you can scroll to it. Here's how to do it:

        //move the caret to the end of the text         textBox.SelectionStart = textBox.TextLength;         //scroll to the caret         textBox.ScrollToCaret(); 
like image 98
Doctor Jones Avatar answered Sep 22 '22 02:09

Doctor Jones


This is a bit of an old question, but none of the suggested answers worked for me (ScrollToCaret() only works when the TextBox has focus). So in case any more should be searching for this at some point, I thought I'd share what I found to be the solution:

public class Utils {     [DllImport("user32.dll", CharSet = CharSet.Auto)]     private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);      private const int WM_VSCROLL = 0x115;     private const int SB_BOTTOM = 7;      /// <summary>     /// Scrolls the vertical scroll bar of a multi-line text box to the bottom.     /// </summary>     /// <param name="tb">The text box to scroll</param>     public static void ScrollToBottom(TextBox tb)     {         SendMessage(tb.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero);     } } 

Credit for the solution should go to this post at bytes.com: http://bytes.com/topic/c-sharp/answers/248500-scroll-bottom-textbox#post1005377

like image 39
Julian Avatar answered Sep 20 '22 02:09

Julian