修复了 windows 表单应用程序中 TextBox 内的文本(或标签)
Fixed text(or label) inside a TextBox in windows form applications
我想知道是否可以将标签形式的固定文本添加到不可移动的文本框,然后可以将任何文本添加到文本框。标签必须在里面,标签后面不能有任何一行。
这里提供了两个简单的答案:
第一的:
我使用事件添加了一些等于标签大小的空格:
private void textBox2_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length <= label2.Text.Length)
{
for (var i = 0; i < label2.Text.Length; i++)
{
textBox2.AppendText(" ");
}
;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.Length == label2.Text.Length)
{
var temp = textBox2.Text;
textBox2.Clear();
textBox2.AppendText(" ");
textBox2.AppendText(temp);
}
}
第二:通过使用 IntPtr SendMessage
作为新的控件,@reza-aghaei 回答了我在这里写下的内容:
public class SampleTextBox : 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_LEFTMARGIN = 1;
private Label label;
public SampleTextBox() : base()
{
label = new Label() { Text = "http://", Dock = DockStyle.Left, AutoSize = true };
this.Controls.Add(label);
}
public string Label
{
get { return label.Text; }
set { label.Text = value; if (IsHandleCreated) SetMargin(); }
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
SetMargin();
}
private void SetMargin()
{
SendMessage(this.Handle, EM_SETMARGINS, EC_LEFTMARGIN, label.Width);
}
}
此控件存在一个很大的问题,当更改 RightToLeft 时,文本无法正常工作 属性。
我想知道是否可以将标签形式的固定文本添加到不可移动的文本框,然后可以将任何文本添加到文本框。标签必须在里面,标签后面不能有任何一行。
这里提供了两个简单的答案: 第一的: 我使用事件添加了一些等于标签大小的空格:
private void textBox2_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length <= label2.Text.Length)
{
for (var i = 0; i < label2.Text.Length; i++)
{
textBox2.AppendText(" ");
}
;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.Length == label2.Text.Length)
{
var temp = textBox2.Text;
textBox2.Clear();
textBox2.AppendText(" ");
textBox2.AppendText(temp);
}
}
第二:通过使用 IntPtr SendMessage
作为新的控件,@reza-aghaei 回答了我在这里写下的内容:
public class SampleTextBox : 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_LEFTMARGIN = 1;
private Label label;
public SampleTextBox() : base()
{
label = new Label() { Text = "http://", Dock = DockStyle.Left, AutoSize = true };
this.Controls.Add(label);
}
public string Label
{
get { return label.Text; }
set { label.Text = value; if (IsHandleCreated) SetMargin(); }
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
SetMargin();
}
private void SetMargin()
{
SendMessage(this.Handle, EM_SETMARGINS, EC_LEFTMARGIN, label.Width);
}
}
此控件存在一个很大的问题,当更改 RightToLeft 时,文本无法正常工作 属性。