0

我正在按照这个答案制作一个自动滚动文本框。

文本框有一些初始文本,因此滚动条将显示在开头。

问题是当我拖动窗体的边框以放大文本框时,滚动条消失后我会立即收到“创建窗口句柄时出错”异常。

我该如何解决?

这是代码:

public class AutoScrollTextBox : TextBox
{
    private bool mScrollbars;

    public AutoScrollTextBox()
    {
        Multiline = true;
        Dock = DockStyle.Fill;
        Font = new System.Drawing.Font("Courier New", 9);
    }

    private void checkForScrollbars()
    {
        if (!IsHandleCreated)
            return;

        bool scroll = false;
        int cnt = this.Lines.Length;
        if (cnt > 1)
        {
            int ch0 = this.GetFirstCharIndexFromLine(0);
            int pos0 = this.GetPositionFromCharIndex(ch0).Y;
            if (pos0 >= 32768) pos0 -= 65536;
            int ch1 = this.GetFirstCharIndexFromLine(1);
            int pos1 = this.GetPositionFromCharIndex(ch1).Y;
            if (pos1 >= 32768) pos1 -= 65536;
            int h = pos1 - pos0;
            scroll = cnt * h > (this.ClientSize.Height - 6);  // 6 = padding
            Debug.WriteLine($"scroll:{scroll},cnt:{cnt},h:{h},CH:{ClientSize.Height},ch0:{ch0},y0:{pos0},ch1:{ch1},y1:{pos1}");
        }
        if (scroll != mScrollbars)
        {
            mScrollbars = scroll;
            this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None;
        }
    }

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

我从输出窗口得到的日志:

......
scroll:True,cnt:21,h:15,CH:314,ch0:0,y0:1,ch1:35,y1:16
scroll:True,cnt:21,h:15,CH:315,ch0:0,y0:1,ch1:35,y1:16
scroll:True,cnt:21,h:15,CH:317,ch0:0,y0:1,ch1:35,y1:16
scroll:True,cnt:21,h:15,CH:318,ch0:0,y0:1,ch1:35,y1:16
scroll:True,cnt:21,h:15,CH:320,ch0:0,y0:1,ch1:35,y1:16
scroll:False,cnt:21,h:15,CH:321,ch0:0,y0:1,ch1:35,y1:16
scroll:True,cnt:21,h:16,CH:321,ch0:0,y0:1,ch1:35,y1:17

Exception thrown: 'System.ComponentModel.Win32Exception' in System.Windows.Forms.dll

System.ComponentModel.Win32Exception (0x80004005): Error creating window handle.
   at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
   at System.Windows.Forms.Control.CreateHandle()
   at System.Windows.Forms.TextBoxBase.CreateHandle()
   at System.Windows.Forms.Control.RecreateHandleCore()
   at System.Windows.Forms.TextBox.set_ScrollBars(ScrollBars value)
   at MessageTester.AutoScrollTextBox.checkForScrollbars()
   at MessageTester.AutoScrollTextBox.OnClientSizeChanged(EventArgs e)
......
4

0 回答 0