添加标签文本框控件内 [英] Add label inside textbox control

查看:138
本文介绍了添加标签文本框控件内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望做一个控制,从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;
  }
}

结果:

这篇关于添加标签文本框控件内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆