添加标签文本框控件内控件、文本框、标签

2023-09-04 22:37:41 作者:兄弟大于天ζ㎜/

我希望做一个控制,从TextBox继承并具有一个标签在其内部大棒右侧的文本框中,哪些文本不是用户可编辑的,而是由一个属性设置。如何才能做到这一点?我意识到可能有很多原因,这UX是一个坏主意,但我必须这样做,这样一来。

I want to make a control which inherits from TextBox and which has a label inside which "sticks" to the right side of the text box and which text is not user-editable but rather is set by a property. How can this be done? I realize there may be many reasons why this UX is a bad idea, but I have to do it this way.

推荐答案

从汉斯帕桑特的按钮适应里面的WinForms文本框回答:

public class TextBoxWithLabel : TextBox {

  [DllImport("user32.dll")]
  private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

  Label label = new Label();

  public TextBoxWithLabel() {
    label.BackColor = Color.LightGray;
    label.Cursor = Cursors.Default;
    label.TextAlign = ContentAlignment.MiddleRight;
    this.Controls.Add(label);
  }

  private int LabelWidth() {
    return TextRenderer.MeasureText(label.Text, label.Font).Width;
  }

  public string LabelText {
    get { return label.Text; }
    set {
      label.Text = value;
      SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(LabelWidth() << 16));
      OnResize(EventArgs.Empty);
    }
  }

  protected override void OnResize(EventArgs e) {
    base.OnResize(e);
    int labelWidth = LabelWidth();
    label.Left = this.ClientSize.Width - labelWidth;
    label.Top = (this.ClientSize.Height / 2) - (label.Height / 2);
    label.Width = labelWidth;
    label.Height = this.ClientSize.Height;
  }
}

结果: