TextBox String/Text 的自定义控件的填充

TextBox String/Text's Padding For Custom Control

我是新手,最近我问了这个 ,它教我为 TextBox 的底部边框设置最佳选项,防止 flickering/tearing - 由绘制图形产生.

现在我的问题是如何为文本框内的 text/string 添加 margin/paddings,代码如下:

using System.Drawing;
using System.Windows.Forms;

namespace main.Classes.CustomControls {

    class TextBoxMaterial : TextBox {
        public TextBoxMaterial() {
            this.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.Controls.Add(new Label() {
                Height = 2,
                Dock = DockStyle.Bottom,
                BackColor = Color.Gray,
            });
        }
    }
}

当前文本框:

我需要的东西:

我认为您必须继承 UserControl 而不是 TextBox,并向 UserControl 添加一个 TextBox。下面的代码绝不是完整的,但应该向您展示我在说什么

public partial class TextBoxMaterial : UserControl
{
    public TextBoxMaterial()
    {
        InitializeComponent();

        this.Controls.Add(new Label()
        {
            Height = 2,
            Dock = DockStyle.Bottom,
            BackColor = Color.Gray,
        });

        this.Controls.Add(new TextBox()
        {
            Left = 10,
            Width = this.Width - 20,
            BackColor = this.BackColor,
            BorderStyle = BorderStyle.None,
         });
    }
}

您可以通过发送 EM_SETMARGINSTextBox 的文本设置左填充和右填充。您还可以将 TextBoxAutoSize 属性 设置为 false,以便能够更改控件的高度。 这是结果:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
public class ExTextBox : TextBox
{
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hwnd, int msg,
        int wParam, int lParam);
    private const int EM_SETMARGINS = 0xd3;
    private const int EC_RIGHTMARGIN = 2;
    private const int EC_LEFTMARGIN = 1;
    private int p = 10;
    public ExTextBox()
        : base()
    {
        var b = new Label { Dock = DockStyle.Bottom, Height = 2, BackColor = Color.Gray };
        var l = new Label { Dock = DockStyle.Left, Width = p, BackColor = Color.White };
        var r = new Label { Dock = DockStyle.Right, Width = p, BackColor = Color.White };
        AutoSize = false;
        Padding = new Padding(0);
        BorderStyle = System.Windows.Forms.BorderStyle.None;
        Controls.AddRange(new Control[] { l, r, b });
    }
    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        SetMargin();
    }
    private void SetMargin()
    {
        SendMessage(Handle, EM_SETMARGINS, EC_RIGHTMARGIN, p << 16);
        SendMessage(Handle, EM_SETMARGINS, EC_LEFTMARGIN, p);
    }
}

要知道右标签的作用是什么,尽量不加到控件中,然后写一段长文本到TextBox,然后按方向键到文本末尾,再回到开头使用箭头键。