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

查看:22
本文介绍了仅当文本不适合时,如何在 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.

这是一个只读文本框,仅用于显示.它是一个文本框,以便用户可以将文本复制出来.是否有内置支持滚动条自动显示的功能?如果不是,我应该使用不同的控件吗?还是我需要挂钩 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天全站免登陆