仅当文本不合适时,如何在System.Windows.Forms.TextBox上显示滚动条? [英] How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit?

查看:141
本文介绍了仅当文本不合适时,如何在System.Windows.Forms.TextBox上显示滚动条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有Multiline = True的System.Windows.Forms.TextBox,我只想在文本不适合时显示滚动条.

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

这是一个只读文本框,仅用于显示.这是一个TextBox,以便用户可以复制文本.有内置支持滚动条自动显示的功能吗?如果没有,我应该使用其他控件吗?还是我需要钩住TextChanged并手动检查是否溢出(如果是,那么如何确定文本是否适合?)

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

WordWrap和Scrollbars设置的各种组合没有任何运气.我希望最初没有滚动条,只有在文本不符合给定方向的情况下,每个滚动条才会动态显示.

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.

@nobugz,谢谢,在禁用WordWrap时可以使用.我不希望禁用自动换行,但这是两种弊端中的较小者.

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

@AndréNeves,很好,如果用户可以编辑,我会采用这种方式.我同意一致性是UI直观性的基本规则.

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

推荐答案

向您的项目添加一个新类,并粘贴以下代码.编译.将新控件从工具箱的顶部拖放到您的窗体上.它不是很完美,但应该为您工作.

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.

using System;
using System.Drawing;
using System.Windows.Forms;

public class MyTextBox : TextBox {
  private bool mScrollbars;
  public MyTextBox() {
    this.Multiline = true;
    this.ReadOnly = true;
  }
  private void checkForScrollbars() {
    bool scroll = false;
    int cnt = this.Lines.Length;
    if (cnt > 1) {
      int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y;
      if (pos0 >= 32768) pos0 -= 65536;
      int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y;
      if (pos1 >= 32768) pos1 -= 65536;
      int h = pos1 - pos0;
      scroll = cnt * h > (this.ClientSize.Height - 6);  // 6 = padding
    }
    if (scroll != mScrollbars) {
      mScrollbars = scroll;
      this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;
    }
  }

  protected override void OnTextChanged(EventArgs e) {
    checkForScrollbars();
    base.OnTextChanged(e);
  }

  protected override void OnClientSizeChanged(EventArgs e) {
    checkForScrollbars();
    base.OnClientSizeChanged(e);
  }
}

这篇关于仅当文本不合适时,如何在System.Windows.Forms.TextBox上显示滚动条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆