c#-用于自定义控件的文本框字符串/文本填充
作者:互联网
我是新手,最近我问了这个question,它告诉我在TextBox的底部边框上有我的最佳选择,它可以防止由于绘制图形而导致的闪烁/撕裂.
现在我的问题是如何在文本框中包含文本/字符串的边距/填充,这是代码:
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,
});
}
}
}
当前文本框:
我需要具备的条件:
解决方法:
您可以通过发送EM_SETMARGINS
来设置TextBox文本的左填充和右填充.还可以将TextBox的AutoSize属性设置为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并通过箭头键转到文本的结尾,然后再使用箭头键回到开头.
标签:margins,padding,c,user-interface,winforms 来源: https://codeday.me/bug/20191118/2027865.html