用于自定义控件的TextBox字符串/文本填充 [英] TextBox String/Text's Padding For Custom Control

查看:125
本文介绍了用于自定义控件的TextBox字符串/文本填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,最近我问了这个

I'm a newbie, and recently I've asked this question, where it taught me to have my best option for TextBox's bottom border, that prevents flickering/tearing - resulted by drawn graphics.

现在我的问题是如何在文本框内为文本/字符串添加边距/填充,这是代码:

Now my problem is how to have margin/paddings for the text/string inside the textbox, here's the code:

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

当前文本框:

推荐答案

您可以通过发送

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

要知道右标签的作用,请尝试不将其添加到控件中,然后将长文本写入TextBox,然后使用箭头键转到文本的末尾,然后再使用箭头键返回到开头.

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.

这篇关于用于自定义控件的TextBox字符串/文本填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆