<p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p>

<p>This is a readonly textbox used only for display.  It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check  for overflow (if so, how to tell if the text fits?)</p>

<hr/>

<p>Not having any luck with various combinations of WordWrap and Scrollbars settings.  I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p>

<hr/>

<p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p>

<hr/>

<p>@André Neves, good point, and I would go that way if it was user-editable.  I agree that consistency is the cardinal rule for UI intuitiveness.</p>

[{'answer_id': 73173, 'author': 'André Chalella', 'author_id': 4850, 'author_profile': 'https://Stackoverflow.com/users/4850', 'pm_score': 3, 'selected': False, 'text': "<p>I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and <code>WordWrap == false</code>.</p>\n\n<p>I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!</p>\n\n<p>Perhaps it would be a good idea just to let your application follow Windows' look and feel.</p>\n"}, {'answer_id': 89428, 'author': 'Hans Passant', 'author_id': 17034, 'author_profile': 'https://Stackoverflow.com/users/17034', 'pm_score': 5, 'selected': True, 'text': "<p>Add a new class to your project and paste the code shown below.  Compile.  Drop the new control from the top of the toolbox onto your form.  It's not quite perfect but ought to work for you.</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyTextBox : TextBox {\n  private bool mScrollbars;\n  public MyTextBox() {\n    this.Multiline = true;\n    this.ReadOnly = true;\n  }\n  private void checkForScrollbars() {\n    bool scroll = false;\n    int cnt = this.Lines.Length;\n    if (cnt &gt; 1) {\n      int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;\n      if (pos0 &gt;= 32768) pos0 -= 65536;\n      int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;\n      if (pos1 &gt;= 32768) pos1 -= 65536;\n      int h = pos1 - pos0;\n      scroll = cnt * h &gt; (this.ClientSize.Height - 6);  // 6 = padding\n    }\n    if (scroll != mScrollbars) {\n      mScrollbars = scroll;\n      this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;\n    }\n  }\n\n  protected override void OnTextChanged(EventArgs e) {\n    checkForScrollbars();\n    base.OnTextChanged(e);\n  }\n\n  protected override void OnClientSizeChanged(EventArgs e) {\n    checkForScrollbars();\n    base.OnClientSizeChanged(e);\n  }\n}\n</code></pre>\n"}, {'answer_id': 612234, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>I came across this question when I wanted to solve the same problem. </p>\n\n<p>The easiest way to do it is to change to System.Windows.Forms.RichTextBox. The ScrollBars property in this case can be left to the default value of RichTextBoxScrollBars.Both, which indicates "Display both a horizontal and a vertical scroll bar when needed." It would be nice if this functionality were provided on TextBox.</p>\n'}, {'answer_id': 666731, 'author': 'yagni', 'author_id': 80525, 'author_profile': 'https://Stackoverflow.com/users/80525', 'pm_score': 3, 'selected': False, 'text': "<p>There's an extremely subtle bug in nobugz's solution that results in a heap corruption, but only if you're using AppendText() to update the TextBox.</p>\n\n<p>Setting the ScrollBars property from OnTextChanged will cause the Win32 window (handle) to be destroyed and recreated. But OnTextChanged is called from the bowels of the Win32 edit control (EditML_InsertText), which immediately thereafter expects the internal state of that Win32 edit control to be unchanged. Unfortunately, since the window is recreated, that internal state has been freed by the OS, resulting in an access violation.</p>\n\n<p>So the moral of the story is: don't use AppendText() if you're going to use nobugz's solution.</p>\n"}, {'answer_id': 4147348, 'author': 'b8adamson', 'author_id': 215954, 'author_profile': 'https://Stackoverflow.com/users/215954', 'pm_score': 2, 'selected': False, 'text': '<p>I had some success with the code below.</p>\n\n<pre><code>  public partial class MyTextBox : TextBox\n  {\n    private bool mShowScrollBar = false;\n\n    public MyTextBox()\n    {\n      InitializeComponent();\n\n      checkForScrollbars();\n    }\n\n    private void checkForScrollbars()\n    {\n      bool showScrollBar = false;\n      int padding = (this.BorderStyle == BorderStyle.Fixed3D) ? 14 : 10;\n\n      using (Graphics g = this.CreateGraphics())\n      {\n        // Calcualte the size of the text area.\n        SizeF textArea = g.MeasureString(this.Text,\n                                         this.Font,\n                                         this.Bounds.Width - padding);\n\n        if (this.Text.EndsWith(Environment.NewLine))\n        {\n          // Include the height of a trailing new line in the height calculation        \n          textArea.Height += g.MeasureString("A", this.Font).Height;\n        }\n\n        // Show the vertical ScrollBar if the text area\n        // is taller than the control.\n        showScrollBar = (Math.Ceiling(textArea.Height) &gt;= (this.Bounds.Height - padding));\n\n        if (showScrollBar != mShowScrollBar)\n        {\n          mShowScrollBar = showScrollBar;\n          this.ScrollBars = showScrollBar ? ScrollBars.Vertical : ScrollBars.None;\n        }\n      }\n    }\n\n    protected override void OnTextChanged(EventArgs e)\n    {\n      checkForScrollbars();\n      base.OnTextChanged(e);\n    }\n\n    protected override void OnResize(EventArgs e)\n    {\n      checkForScrollbars();\n      base.OnResize(e);\n    }\n  }\n</code></pre>\n'}, {'answer_id': 25197797, 'author': 'Michael Csikos', 'author_id': 1484559, 'author_profile': 'https://Stackoverflow.com/users/1484559', 'pm_score': 0, 'selected': False, 'text': "<p>What Aidan describes is almost exactly the UI scenario I am facing. As the text box is read only, I don't need it to respond to TextChanged. And I'd prefer the auto-scroll recalculation to be delayed so it's not firing dozens of times per second while a window is being resized.</p>\n\n<p>For most UIs, text boxes with both vertical and horizontal scroll bars are, well, evil, so I'm only interested in vertical scroll bars here.</p>\n\n<p>I also found that MeasureString produced a height that was actually bigger than what was required. Using the text box's PreferredHeight with no border as the line height gives a better result.</p>\n\n<p>The following seems to work pretty well, with or without a border, and it works with WordWrap on.</p>\n\n<p>Simply call AutoScrollVertically() when you need it, and optionally specify recalculateOnResize.</p>\n\n<pre><code>public class TextBoxAutoScroll : TextBox\n{\n    public void AutoScrollVertically(bool recalculateOnResize = false)\n    {\n        SuspendLayout();\n\n        if (recalculateOnResize)\n        {\n            Resize -= OnResize;\n            Resize += OnResize;\n        }\n\n        float linesHeight = 0;\n        var   borderStyle = BorderStyle;\n\n        BorderStyle       = BorderStyle.None;\n\n        int textHeight    = PreferredHeight;\n\n        try\n        {\n            using (var graphics = CreateGraphics())\n            {\n                foreach (var text in Lines)\n                {\n                    var textArea = graphics.MeasureString(text, Font);\n\n                    if (textArea.Width &lt; Width)\n                        linesHeight += textHeight;\n                    else\n                    {\n                        var numLines = (float)Math.Ceiling(textArea.Width / Width);\n\n                        linesHeight += textHeight * numLines;\n                    }\n                }\n            }\n\n            if (linesHeight &gt; Height)\n                ScrollBars = ScrollBars.Vertical;\n            else\n                ScrollBars = ScrollBars.None;\n        }\n        catch (Exception ex)\n        {\n            System.Diagnostics.Debug.WriteLine(ex);\n        }\n        finally\n        {\n            BorderStyle = borderStyle;\n\n            ResumeLayout();\n        }\n    }\n\n    private void OnResize(object sender, EventArgs e)\n    {\n        m_timerResize.Stop();\n\n        m_timerResize.Tick    -= OnDelayedResize;\n        m_timerResize.Tick    += OnDelayedResize;\n        m_timerResize.Interval = 475;\n\n        m_timerResize.Start();\n    }\n\n    Timer m_timerResize = new Timer();\n\n    private void OnDelayedResize(object sender, EventArgs e)\n    {\n        m_timerResize.Stop();\n\n        Resize -= OnResize;\n\n        AutoScrollVertically();\n\n        Resize += OnResize;\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/73110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1042/']