首页 > 解决方案 > 修复了 Windows 窗体应用程序中 TextBox 内的文本(或标签)

问题描述

我想知道是否可以将标签形式的固定文本添加到不可移动的文本框中,然后可以将任何文本添加到文本框。标签必须在里面,标签后面不能有任何一行。

标签: c#winformscontrols

解决方案


这里提供了两个简单的答案:首先:我使用事件添加了一些等于标签大小的空格:

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 属性时,该控件的文本无法正常工作存在一个相当大的问题。


推荐阅读