TextBox String/Text's Padding For Custom Control

拟墨画扇 提交于 2019-12-01 09:21:42

You can set left padding and right padding for text of TextBox by sending an EM_SETMARGINS. You also can set AutoSize property of the TextBox to false to be able to change the height of control. Here is the result:

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);
    }
}

To know what the role of right label is, try not adding it to the control, then write a long text to TextBox and go to the end of text by arrow keys and again back to the beginning using arrow keys.

I think you will have to inherit from UserControl rather than from TextBox and add a TextBox to your UserControl. Code below is by no means complete but should show you what I'm talking about

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,
         });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!