我想创建一个从 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.
改编自 Hans Passant 的 Winforms 文本框内的按钮答案:
Adapting from Hans Passant's Button inside a winforms textbox answer:
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;
}
}
结果:
这篇关于在文本框控件内添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!