根据内容调整RichTextBox的大小

P.B*_*key 8 c# winforms

此代码根据其内容自动调整RichTextBox的大小.我遇到了问题,尤其是桌子. \t可能会被忽略.我尝试了托管解决方案,现在我正在尝试平台调用.电流输出:

在此输入图像描述

    [DllImport("gdi32.dll")]
    static extern bool GetTextExtentPoint32(IntPtr hdc, string lpString, int cbString, out SIZE lpSize);

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr GetDC(IntPtr hWnd);

    [StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct SIZE
    {
        public int cx;
        public int cy;

        public SIZE(int cx, int cy)
        {
            this.cx = cx;
            this.cy = cy;
        }
    }

    public static void Main()
    {
        Form form = new Form();
        RichTextBox rtfBox = new RichTextBox();

        rtfBox.Rtf = @"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil Arial;}}\viewkind4\uc1\trowd\trgaph100\cellx1000\cellx2000\pard\intbl\lang1033\f0\fs20  hi\cell  bye\cell\row\intbl  one\cell  two\cell\row\pard\par}";
        rtfBox.ScrollBars = RichTextBoxScrollBars.None;

        string sInput = "hi\t bye\t\n";// one\t two\t\n";
        SIZE CharSize;

        form.Controls.Add(rtfBox);

        IntPtr hdc = GetDC(IntPtr.Zero);//Context for entire screen
        GetTextExtentPoint32(hdc, sInput, sInput.Length, out CharSize);

        rtfBox.Width = CharSize.cx;
        rtfBox.Height = CharSize.cy;

        form.Visible = false;

        form.ShowDialog();
    }
Run Code Online (Sandbox Code Playgroud)

(注意,为简单起见,这是一个控制台应用程序,引用了System.Windows.Forms.dll)

adr*_*nks 13

你看过这个ContentsResized活动了吗?在事件触发时添加以下方法以进行调用:

private void richTextBox_ContentsResized(object sender, ContentsResizedEventArgs e)
{
    var richTextBox = (RichTextBox) sender;
    richTextBox.Width = e.NewRectangle.Width;
    richTextBox.Height = e.NewRectangle.Height;
}
Run Code Online (Sandbox Code Playgroud)

当RTF内容更改(使用Rtf)时,RichTextBox应调整其大小以匹配其内容.确保您还将WordWrap属性设置为false.


我已经尝试了你的表示例,它似乎工作(虽然有一点偏移,你可以通过添加几个像素的宽度到调整大小解决 - 不知道为什么会发生这种情况):

P.Brian.Mackey编辑
这个答案对我有用.为了澄清,这里是包括边界修复的最终代码:

    public static void Main()
    {
        string sInput = "hi\t bye\t\n";// one\t two\t\n";
        SIZE CharSize;
        Form form = new Form();
        RichTextBox rtfBox = new RichTextBox();
        rtfBox.ContentsResized += (object sender, ContentsResizedEventArgs e) =>
        {
            var richTextBox = (RichTextBox)sender;
            richTextBox.Width = e.NewRectangle.Width;
            richTextBox.Height = e.NewRectangle.Height;
            rtfBox.Width += rtfBox.Margin.Horizontal + SystemInformation.HorizontalResizeBorderThickness;
        };

        rtfBox.WordWrap = false;
        rtfBox.ScrollBars = RichTextBoxScrollBars.None;

        rtfBox.Rtf = @"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil Arial;}}\viewkind4\uc1\trowd\trgaph100\cellx1000\cellx2000\pard\intbl\lang1033\f0\fs20  hi\cell  bye\cell\row\intbl  one\cell  two\cell\row\pard\par}";

        form.Controls.Add(rtfBox);
        form.ShowDialog();
    }
Run Code Online (Sandbox Code Playgroud)