c# - 修复了 Windows 窗体应用程序中 TextBox 内的文本(或标签)
问题描述
我想知道是否可以将标签形式的固定文本添加到不可移动的文本框中,然后可以将任何文本添加到文本框。标签必须在里面,标签后面不能有任何一行。
解决方案
这里提供了两个简单的答案:首先:我使用事件添加了一些等于标签大小的空格:
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 属性时,该控件的文本无法正常工作存在一个相当大的问题。
推荐阅读
- python - 更新单元格值并避免 SettingWithCopyWarning 的最佳方法
- c# - 如何判断 ValidationSummary 是否是从后面的代码触发的?
- powershell - powershell 不理解 trace 作为文本 ex 的一部分。$_.data-action-name
- react-native - 我如何在本机反应中使用里程表?
- arm - 使用 QEMU 安装 ubi 映像时出现问题
- c++ - 固定大小的容器,其中元素被排序,并且可以提供指向 C++ 中数据的原始指针
- assembly - 为什么我会得到另一个结果?
- html - 为什么颜色#e67d22e1 不会在 Safari 中显示?
- reporting-services - 将具有多个详细信息行的 SSRS 报告导出到 CSV 时,会为每个详细信息行生成额外的列
- python - 如何接受无整数类型字段