我是新手,最近我问过这个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,
});
}
}
}
答案 0 :(得分:2)
您可以通过发送EM_SETMARGINS
为TextBox
的文字设置左边距和右边距。您还可以将AutoSize
的{{1}}属性设置为false,以便能够更改控件的高度。
结果如下:
TextBox
要了解正确标签的作用,请尝试不将其添加到控件中,然后将长文本写入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);
}
}
并按箭头键转到文本末尾,然后再使用箭头返回到开头密钥。
答案 1 :(得分:1)
我认为您必须继承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,
});
}
}