如何检查RichTextBox C#中是否存在垂直ScrollBar?

问题描述

我正在将文本附加到RichTextBox。当文本超出RichTextBox的可见区域时,将自动显示“垂直滚动条”。

我想检查是否没有滚动条,但要将Padding设置为5。 滚动条出现,然后填充应为0

private void frmAno_Load(object sender,EventArgs e)
    {
        displayingAnomalies();
        ChangeFormSize();
    }
private void displayingAnomalies()
    {
        int length;
        string heading;
        switch (_lstNullSheet.Count == 0 ? "zero" :
               _lstNullSheet.Count == 1 ? "one" :
               _lstNullSheet.Count > 1 ? "more" : "floor")
        {
            case "zero":
                break;
            case "one":
                heading = "Empty Sheet";
                rtbdisplay.Text = String.Format("{0}\r\n[",heading);
                rtbdisplay.AppendText(_lstNullSheet[0] + "] Sheet in Excel has no data.\r\n\n");
                break;
            case "more":
                heading = "Empty Sheets";
                rtbdisplay.Text = String.Format("{0}\r\n",heading);
               
                foreach(var item in _lstNullSheet)
                {
                    rtbdisplay.AppendText("["+item);
                    length = rtbdisplay.Text.Length;
                    if(_lstNullSheet.Last().Equals(item))
                    {
                        rtbdisplay.AppendText("] Sheets in Excel has no data.afsdfaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n\n");
                        break;
                    }
                    rtbdisplay.AppendText("],");
                    }
                break;
            case "floor":
                break;
            default:
                break;
        }
        _sizetochange = true;
    }
private void ChangeFormSize()
    {
        if(_sizetochange)
        {
           this.Height = 200;
        }
//Here i want to check if scrollbar is present in richtextBox or not 
       if(rtbdisplay.Width - rtbdisplay.ClientSize.Width >= 
        Systeminformation.VerticalScrollBarWidth)
        {
        }
    }

我已经添加了将文本附加到richtextBox代码。然后,我将RichTextBox宽度与滚动条宽度进行比较。

解决方法

(从MSDN论坛获得此内容)

实际上很简单。您必须检查控件的窗口样式中的WS_VSCROLL样式位。

[System.Runtime.InteropServices.DllImport("user32.dll")]
private extern static int GetWindowLong(IntPtr hWnd,int index);

public static bool VerticalScrollBarVisible(Control ctl) {
  int style = GetWindowLong(ctl.Handle,-16);
  return (style & 0x200000) != 0;
}

现在,按如下所示调用函数:

var IsScrollBarVisible = VerticalScrollBarVisible(myRichTextBox);
/// Put your logic here

编辑1

另一种方法可能是:在添加文本之前和之后获取RichTextBox的大小,只需比较文本框的ClientSize值,就可以确定滚动条是否可见,基于宽度。

编辑2

(此编辑的灵感来自您将在下面看到的评论)

WS_SCROLL检查放入文本框的ClientSizeChanged事件中,但是,将其包装在if条件中,如下所示:

private void textbox_ClientSizeChanged(...)
{

 if (VerticalScrollBarVisible(myRichTextbox)
 { 

  //Put your logic here,what you want to do if scrollbar is visible
 }
}