visual textbox1 studio propiedades ejemplo control c# winforms textbox

c# - studio - textbox1 text



¿Cómo implemento un TextBox que muestra "Escriba aquí"? (16)

Mostrar "Escriba aquí para ..." hasta que el usuario ingrese texto en un TextBox es una característica de usabilidad bien conocida hoy en día. ¿Cómo se implementaría esta función en C #?

  1. Establezca textbox.text como "Escriba aquí para ..."

  2. crear un evento, decir box_click ()

  3. -> Pon este código en tu método

    private void box_Click(object sender, EventArgs e) { Textbox b = (Textbox)sender; b.Text = null; }

  4. ahora asigne este método al evento "Enter" de su cuadro de texto (tal vez uno o varios)

Mostrar " Escriba aquí para ... " hasta que el usuario ingrese texto en un TextBox es una característica de usabilidad bien conocida hoy en día. ¿Cómo se implementaría esta función en C #?

Mi idea es anular OnTextChanged , pero la lógica para manejar los cambios de texto desde y hasta " Escribir aquí " es un poco complicado ...

Mostrar " Escriba aquí " en la inicialización y eliminarlo en la primera entrada es fácil, pero quiero mostrar el mensaje cada vez que el texto ingresado se vuelva vacío.


¿Por qué usar OnTextChanged? Sugeriría quitar el texto "Escriba aquí" cuando TextBox obtiene el foco. Cuando el control pierde el foco y no se ingresa texto, puede mostrar el texto nuevamente.

El mismo resultado y sin necesidad de lógica engañosa.


Algo que me ha funcionado:

this.waterMarkActive = true; this.textBox.ForeColor = Color.Gray; this.textBox.Text = "Type here"; this.textBox.GotFocus += (source, e) => { if (this.waterMarkActive) { this.waterMarkActive = false; this.textBox.Text = ""; this.textBox.ForeColor = Color.Black; } }; this.textBox.LostFocus += (source, e) => { if (!this.waterMarkActive && string.IsNullOrEmpty(this.textBox.Text)) { this.waterMarkActive = true; this.textBox.Text = "Type here"; this.textBox.ForeColor = Color.Gray; } };

Donde bool waterMarkActive es una variable miembro de clase y textBox es el TextBox . Esto probablemente debería ser encapsulado :) Podrían haber algunos problemas con este enfoque, pero actualmente no estoy al tanto de ninguno.

Recientemente descubrí que Windows admite marcas de agua en cuadros de texto; se les llama pancartas de referencia (ver here ). Es muy fácil de implementar:

// Within your class or scoped in a more appropriate location: [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); // In your constructor or somewhere more suitable: SendMessage(textBox.Handle, 0x1501, 1, "Please type here.");

Donde textBox es una instancia de TextBox , 0x1501 es el código del mensaje de Windows EM_SETCUEBANNER , el wParam puede ser TRUE (distinto de cero) o FALSE (cero), y lParam es la marca de agua que le gustaría mostrar. wParam indica cuándo se debe mostrar el letrero; si se establece en TRUE , el cartel de señal se mostrará incluso cuando el control tenga foco.


Basado en la respuesta de @ Joel. Arreglé su clase (¡gracias por la base!)

/// <summary> /// A textbox that supports a watermak hint. /// Based on: https://.com/a/15232752 /// </summary> public class WatermarkTextBox : TextBox { /// <summary> /// The text that will be presented as the watermak hint /// </summary> private string _watermarkText; /// <summary> /// Gets or Sets the text that will be presented as the watermak hint /// </summary> public string WatermarkText { get { return _watermarkText; } set { _watermarkText = value; } } /// <summary> /// Whether watermark effect is enabled or not /// </summary> private bool _watermarkActive; /// <summary> /// Gets or Sets whether watermark effect is enabled or not /// </summary> public bool WatermarkActive { get { return _watermarkActive; } set { _watermarkActive = value; } } /// <summary> /// Create a new TextBox that supports watermak hint /// </summary> public WatermarkTextBox() { this.WatermarkActive = _watermarkActive; this.Text = _watermarkText; } protected override void OnCreateControl() { base.OnCreateControl(); if (this.WatermarkActive) CheckWatermark(); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); CheckWatermark(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); CheckWatermark(); } public void CheckWatermark() { if ((this.WatermarkActive) && String.IsNullOrWhiteSpace(this.Text)) { ForeColor = Color.Gray; this.Text = _watermarkText; } else if ((this.WatermarkActive) && (!String.IsNullOrWhiteSpace(this.Text))) { if (this.Text == _watermarkText) this.Text = ""; ForeColor = Color.Black; } else ForeColor = Color.Black; } }


Basado en la respuesta de @ Pooven (¡gracias!), Creé esta clase. Funciona para mi.

/// <summary> /// A textbox that supports a watermak hint. /// </summary> public class WatermarkTextBox : TextBox { /// <summary> /// The text that will be presented as the watermak hint /// </summary> private string _watermarkText = "Type here"; /// <summary> /// Gets or Sets the text that will be presented as the watermak hint /// </summary> public string WatermarkText { get { return _watermarkText; } set { _watermarkText = value; } } /// <summary> /// Whether watermark effect is enabled or not /// </summary> private bool _watermarkActive = true; /// <summary> /// Gets or Sets whether watermark effect is enabled or not /// </summary> public bool WatermarkActive { get { return _watermarkActive; } set { _watermarkActive = value; } } /// <summary> /// Create a new TextBox that supports watermak hint /// </summary> public WatermarkTextBox() { this._watermarkActive = true; this.Text = _watermarkText; this.ForeColor = Color.Gray; GotFocus += (source, e) => { RemoveWatermak(); }; LostFocus += (source, e) => { ApplyWatermark(); }; } /// <summary> /// Remove watermark from the textbox /// </summary> public void RemoveWatermak() { if (this._watermarkActive) { this._watermarkActive = false; this.Text = ""; this.ForeColor = Color.Black; } } /// <summary> /// Applywatermak immediately /// </summary> public void ApplyWatermark() { if (!this._watermarkActive && string.IsNullOrEmpty(this.Text) || ForeColor == Color.Gray ) { this._watermarkActive = true; this.Text = _watermarkText; this.ForeColor = Color.Gray; } } /// <summary> /// Apply watermak to the textbox. /// </summary> /// <param name="newText">Text to apply</param> public void ApplyWatermark(string newText) { WatermarkText = newText; ApplyWatermark(); } }


En la última versión de C #, TextBox tiene la propiedad PlaceholderText, que hace todo el trabajo. Por lo tanto, solo tiene que establecer "Escriba aquí ..." como valor de esta propiedad.


Estoy empezando a aprender C # este semestre, así que no soy un experto, pero esto funcionó para mí: (Esto es mediante el uso de formularios de Windows)

private void Form1_Load(object sender, EventArgs e) { textBox1.SelectionStart = 0; //This keeps the text textBox1.SelectionLength = 0; //from being highlighted textBox1.ForeColor = Color.Gray; } private void textBox_MouseMove(object sender, MouseEventArgs e) { Cursor.Current = Cursors.IBeam; //Without this the mouse pointer shows busy } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (textBox1.Text.Equals("Type here...") == true) { textBox1.Text = ""; textBox1.ForeColor = Color.Black; } } private void textBox1_KeyUp(object sender, KeyEventArgs e) { if (textBox1.Text.Equals(null) == true || textBox1.Text.Equals("") == true) { textBox1.Text = "Type here..."; textBox1.ForeColor = Color.Gray; } }


Lo que estás buscando es un texbox con " marca de agua "

Hay una implementación de muestra para C # here .

Espero eso ayude


Maneje el evento de foco perdido y si la propiedad Texto está vacía, llénelo con su cadena predeterminada.


Puede dibujar la cadena "Escribir aquí" en el fondo del cuadro de texto hasta que se vacíe


Según la respuesta de Ahmed Soliman Flasha, use la siguiente clase:

public class TextBoxHint : TextBox { string _hint; [Localizable(true)] public string Hint { get { return _hint; } set { _hint = value; OnHintChanged(); } } protected virtual void OnHintChanged() { SendMessage(this.Handle, EM_SETCUEBANNER, 1, _hint); } const int EM_SETCUEBANNER = 0x1501; [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam); }


Si desea evitar el control del cambio de tamaño de los problemas y los problemas de enlace de datos y simplificar el código (vale, es cuestionable), puede usar una etiqueta y alternar su visibilidad. Entonces

private void FilterComboBox_GotFocus(object sender, EventArgs e) { FilterWatermarkLabel.Visible = false; } private void FilterComboBox_LostFocus(object sender, EventArgs e) { if (!FilterWatermarkLabel.Visible && string.IsNullOrEmpty(FilterComboBox.Text)) { FilterWatermarkLabel.Visible = true; } }

Otro enfoque para las imágenes y también para evitar problemas de enlace de datos está aquí https://msdn.microsoft.com/en-us/library/bb613590(v=vs.100).aspx


Si esto es ASP.NET (a diferencia de las formas de ganar), puede hacer esto:

Si está utilizando jQuery, agregue esto a su documento listo (o como quiera que inicialice su página):

var $textbox = $("textbox selector"); // assumes you select a single text box if ($textbox.val() == "") { $textbox.val("Type here to..."); $textbox.one(''focus'', function() { $(this).attr(''value'', ''''); }); }

Tendrá que hacer algunas refactorizaciones pequeñas si está seleccionando más de un cuadro de texto (ponga la instrucción if dentro de cada uno en el elemento).


Si esto es para ASP.NET, entonces puedes probar TextBoxWatermark .

Si esto es para Windows Forms, esto ya está respondido here en SO.


PRODUCE UNA SALIDA SIMILAR A WATERMARK HTML

Aquí está mi código para el texto de la "marca de agua" o el texto de "vista previa": ¡funciona genial! Usando la aplicación Windows Forms.

NOTA : Este ejemplo tiene 3 cuadros de texto, cada uno tiene el siguiente método para el evento "mouse leave" e "mouse enter" respectivamente.

private void textBoxFav_Leave(object sender, EventArgs e) { TextBox textbox = (TextBox)sender; if (String.IsNullOrWhiteSpace(textbox.Text)) { textbox.ForeColor = Color.Gray; if (textbox.Name == "textBoxFavFood") { textbox.Text = "Favorite Food"; } else if (textbox.Name == "textBoxFavDrink") { textbox.Text = "Favorite Drink"; } else if (textbox.Name == "textBoxFavDesert") { textbox.Text = "Favorite Desert"; } } else { textbox.ForeColor = Color.Black; } } private void textBoxFav_Enter(object sender, EventArgs e) { TextBox textbox = (TextBox)sender; if (textbox.Text == "Favorite Food" || textbox.Text == "Favorite Drink" || textbox.Text == "Favorite Desert") { textbox.Text = ""; textbox.ForeColor = Color.Black; } }


[DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam); const int EM_SETCUEBANNER = 0x1501; public Form1() { InitializeComponent(); SendMessage(textBox1.Handle, EM_SETCUEBANNER, 1, "Username"); SendMessage(textBox2.Handle, EM_SETCUEBANNER, 1, "Password"); }