此代码会根据内容自动调整 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();
}
(注意,为简单起见,这是一个引用了 System.Windows.Forms.dll 的控制台应用程序)
最佳答案
你看过ContentsResized
了吗?事件?添加以下要在事件触发时调用的方法:
private void richTextBox_ContentsResized(object sender, ContentsResizedEventArgs e)
{
var richTextBox = (RichTextBox) sender;
richTextBox.Width = e.NewRectangle.Width;
richTextBox.Height = e.NewRectangle.Height;
}
当 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();
}
关于c# - 根据内容调整 RichTextBox 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906932/