c# - 文本和边框之间的富文本框填充

标签 c# winforms

是否可以在文本和边框之间的富文本框控件中添加填充?

我尝试将一个富文本框停靠在一个面板中,并将其所有四个边的填充设置为 10,这实现了我想要的。除了需要填充的富文本框的垂直滚动条。

最佳答案

EM_GETRECTEM_SETRECT .

将这两者结合起来,你可以做到:

enter image description here

……看起来像这样:

enter image description here

我写了a small C# extension class总结这一切。

使用示例:

const int dist = 24;
richTextBox1.SetInnerMargins(dist, dist, dist, 0);

这会将左侧、顶部和右侧的内边距设置为 24,将底部留为零。

请注意,滚动时,上边距保持不变,如下所示:

enter image description here

就我个人而言,这看起来“不自然”。我希望滚动时上边距也变为零。

也许有一个解决方法......

完整源代码

根据要求:

public static class RichTextBoxExtensions
{
    public static void SetInnerMargins(this TextBoxBase textBox, int left, int top, int right, int bottom)
    {
        var rect = textBox.GetFormattingRect();

        var newRect = new Rectangle(left, top, rect.Width - left - right, rect.Height - top - bottom);
        textBox.SetFormattingRect(newRect);
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public readonly int Left;
        public readonly int Top;
        public readonly int Right;
        public readonly int Bottom;

        private RECT(int left, int top, int right, int bottom)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
        }

        public RECT(Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom)
        {
        }
    }

    [DllImport(@"User32.dll", EntryPoint = @"SendMessage", CharSet = CharSet.Auto)]
    private static extern int SendMessageRefRect(IntPtr hWnd, uint msg, int wParam, ref RECT rect);

    [DllImport(@"user32.dll", EntryPoint = @"SendMessage", CharSet = CharSet.Auto)]
    private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref Rectangle lParam);

    private const int EmGetrect = 0xB2;
    private const int EmSetrect = 0xB3;

    private static void SetFormattingRect(this TextBoxBase textbox, Rectangle rect)
    {
        var rc = new RECT(rect);
        SendMessageRefRect(textbox.Handle, EmSetrect, 0, ref rc);
    }

    private static Rectangle GetFormattingRect(this TextBoxBase textbox)
    {
        var rect = new Rectangle();
        SendMessage(textbox.Handle, EmGetrect, (IntPtr) 0, ref rect);
        return rect;
    }
}

关于c# - 文本和边框之间的富文本框填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2914004/

相关文章:

.net - 当 SelectionMode=FullRowSelect 时,如何突出显示 DataGridView 中的当前单元格

c# - .NET Winform 设置文件位置

c# - 覆盖连续状态存储/恢复算法?

c# - 如何检查工作流是否正在运行。(WF4)

c# - 处理电子邮件时在 C# 中添加 HTML 属性

c# - Crystal 报表列名不明确错误。

c# - 帮助将 csv 文件导入我的 C# 程序

c# - 从 Windows Phone 8.1 发送电子邮件

c# - 在 Google 日历 API 中导入/导出 .ical

c# - 表单未正确加载