在输入字段C#中显示标题

时间:2012-07-22 17:08:29

标签: c# winforms

  

可能重复:
  Watermark TextBox in WinForms

我目前正在编写C#应用程序的设置对话框。 输入字段应如下所示:

Input field emptyInput field filled out

实现这一目标的最佳方法是什么?我想过创建一个背景图片,但我想知道是否有更好的方法(动态的东西)......

4 个答案:

答案 0 :(得分:3)

使用白色设置为BackColor的面板 在面板控件中,在左侧插入TextBoxBorderStyle设为None
在面板控件中,在右侧插入Label,将BackColor设置为Transparent,并将Text设置为"名字"。

enter image description here

答案 1 :(得分:1)

只需创建一个新的文本框类

 public class MyTextBox : TextBox
    {

        public MyTextBox()
        {
            SetStyle(ControlStyles.UserPaint, true);
        }

     protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        this.Invalidate();
    }

        protected override void OnPaint(PaintEventArgs e)
        {

 e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(Color.Black), new System.Drawing.RectangleF(0, 0, this.Width , this.Height ), System.Drawing.StringFormat.GenericDefault);


            e.Graphics.DrawString("Lloyd", this.Font, new SolidBrush(Color.Red), new System.Drawing.RectangleF(0, 0, 100, 100), System.Drawing.StringFormat.GenericTypographic);
            base.OnPaint(e);
        }
    }

对Draw String params进行适当的更改

答案 2 :(得分:1)

我认为这几乎符合您的需求:

public class MyTextBox : TextBox
{
    public const int WM_PAINT = 0x000F;

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_PAINT:
                Invalidate();
                base.WndProc(ref m);
                if (!ContainsFocus && string.IsNullOrEmpty(Text))
                {
                    Graphics gr = CreateGraphics();
                    StringFormat format = new StringFormat();
                    format.Alignment = StringAlignment.Far;

                    gr.DrawString("Enter your name", Font, new SolidBrush(Color.FromArgb(70, ForeColor)), ClientRectangle, format);
                }
                break;
            default:
                base.WndProc(ref m);
                break;
        }
    }
}

在TextBox上覆盖OnPaint通常不是一个好主意,因为插入符号的位置计算错误。

请注意,仅当TextBox为空且没有焦点时才会显示标签。但这就是大多数此类输入框的行为方式。

如果提示始终可见,您只需将其添加为标签:

public class MyTextBox : TextBox
{
    private Label cueLabel;

    public TextBoxWithLabel()
    {
        SuspendLayout();

        cueLabel = new Label();
        cueLabel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
        cueLabel.AutoSize = true;
        cueLabel.Text = "Enter your name";
        Controls.Add(cueLabel);
        cueLabel.Location = new Point(Width - cueLabel.Width, 0);

        ResumeLayout(false);
        PerformLayout();
    }
}

答案 3 :(得分:1)

创建3个控件的合成,并将其放在另一个UserControl中。三个控件将是:

  • 文本框,无边框
  • 标签,位于文本框右侧
  • 面板,带有两个边框。

从Hassan取出食谱,然后将其放在UserControl上,并将其作为一个新的对照使用。