Custom text box management

Is it possible to create a text field in Visual Studio as follows:

+4
source share
3 answers

You just need to handle the three TextBox events, in Designer set the TextBox text to "username" and make it Font Italic, then set the TextBox BackColor to LightYellow, the rest are processed by event handlers ...

private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == "") ChangeTextBoxtoWatermark(); } private void textBox1_MouseEnter(object sender, EventArgs e) { if (textBox1.Text == "username") { textBox1.Text = ""; textBox1.Font = new Font(this.Font, FontStyle.Regular); textBox1.BackColor = Color.White; } } private void textBox1_MouseLeave(object sender, EventArgs e) { if (textBox1.Text == "") ChangeTextBoxtoWatermark(); } private void ChangeTextBoxtoWatermark() { textBox1.Font = new Font(this.Font, FontStyle.Italic); textBox1.BackColor = Color.LightYellow; textBox1.Text = "username"; } 

I checked it and it works great :)

+3
source

Actually. A better solution would be to simply use the Paint event in the text box to draw a line.

Here is the code:

 class CueTextBox : TextBox { public event EventHandler CueTextChanged; private string _cueText; public string CueText { get { return _cueText; } set { value = value ?? string.Empty; if (value != _cueText) { _cueText = value; OnCueTextChanged(EventArgs.Empty); } } } public CueTextBox() : base() { _cueText = string.Empty; } protected virtual void OnCueTextChanged(EventArgs e) { this.Invalidate(true); if (this.CueTextChanged != null) this.CueTextChanged(this, e); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (string.IsNullOrEmpty(this.Text.Trim()) && !string.IsNullOrEmpty(this.CueText) && !this.Focused) { Point startingPoint = new Point(0, 0); StringFormat format = new StringFormat(); Font font = new Font(this.Font.FontFamily.Name, this.Font.Size, FontStyle.Italic); if (this.RightToLeft == RightToLeft.Yes) { format.LineAlignment = StringAlignment.Far; format.FormatFlags = StringFormatFlags.DirectionRightToLeft; } e.Graphics.DrawString(CueText, font, Brushes.Gray, this.ClientRectangle, format); } } const int WM_PAINT = 0x000F; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_PAINT) { this.OnPaint(new PaintEventArgs(Graphics.FromHwnd(m.HWnd), this.ClientRectangle)); } } } 

Now you only need to set the 'CueText' property for the initial value you want, and you're done!

+11
source

This is usually called a "cue."

+2
source

Source: https://habr.com/ru/post/1396015/


All Articles