¿Cómo eliminar el foco de un cuadro de texto en WinForms?


Necesito eliminar el foco de varios cuadros de texto. He intentado usar:

textBox1.Focused = false;

Su valor de propiedad ReadOnly es true.

Luego intenté poner el foco en el formulario, para eliminarlo de todos los cuadros de texto, pero esto tampoco funciona:

this.Focus();

Y la función devuelve false cuando se selecciona un cuadro de texto.

Entonces, ¿cómo elimino el foco de un cuadro de texto?

Author: Shin, 2009-07-17

18 answers

Necesita algún otro control enfocable para mover el enfoque.

Tenga en cuenta que puede establecer el foco en una etiqueta. Es posible que desee considerar dónde desea que la tecla [Tab] lo lleve a continuación.

También tenga en cuenta que no puede configurarlo en el Formulario. Los controles de contenedor como Form y Panel pasarán el Foco a su primer control hijo. Que podría ser el cuadro de texto del que querías que se alejara.

 100
Author: Henk Holterman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-03 06:48:48

Centrarse en la etiqueta no funcionó para mí, haciendo algo como label1.Focus() ¿verdad? el cuadro de texto todavía tiene foco al cargar el formulario, sin embargo tratando Velociraptors respuesta, funcionó para mí, estableciendo el control Activo del Formulario en la etiqueta de esta manera:

private void Form1_Load(object sender, EventArgs e)  
{ 
    this.ActiveControl = label1;       
}
 53
Author: WhySoSerious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 12:10:48

Puede agregar el siguiente código:

this.ActiveControl = null;  //this = form
 35
Author: FTheGodfather,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-29 09:06:30

Intente deshabilitar y habilitar el cuadro de texto.

 31
Author: Spencer Ruport,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-16 20:59:17

También puede establecer la propiedad forms activecontrol a null como

ActiveControl = null;
 16
Author: marcigo36,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-26 08:08:46

Focus establece el foco de entrada, por lo que configurarlo en el formulario no funcionará porque los formularios no aceptan entrada. Intente establecer la propiedad ActiveControl del formulario en un control diferente. También puede usar Select para seleccionar un control específico o SelectNextControl para seleccionar el siguiente control en el orden de tabulación.

 8
Author: Velociraptors,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-16 21:16:35

Prueba este:

Primero configure el orden de tabulación.

Luego en el evento de carga de formulario podemos enviar una tecla de tabulación presionada programáticamente a la aplicación. Por lo que la aplicación dará foco a 1st contol en el orden de pestañas.

En form load incluso escribir esta línea.

SendKeys.Send("{TAB}");

Esto funcionó para mí.

 7
Author: charith rasanga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 12:19:17

Este post me lleva a hacer esto:

ActiveControl = null;

Esto me permite capturar toda la entrada del teclado en el nivel superior sin que otros controles se vuelvan locos.

 4
Author: Kristopher Ives,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-29 05:46:44

Parece que no tengo que poner el foco en ningún otro elemento. En una aplicación de Windows Phone 7, he estado usando el método Focus para quitar el Foco de un cuadro de texto.

Dar el siguiente comando pondrá el foco en nada:

void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        Focus();
    }
}

Http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

Funcionó para mí, pero no se por qué no funcionó para ti: /

 3
Author: Bhawk1990,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-10 17:50:23

Una solución simple sería matar el foco, simplemente crea tu propia clase:

public class ViewOnlyTextBox : System.Windows.Forms.TextBox {
    // constants for the message sending
    const int WM_SETFOCUS = 0x0007;
    const int WM_KILLFOCUS = 0x0008;

    protected override void WndProc(ref Message m) {
        if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;

        base.WndProc (ref m);
    }
}
 3
Author: VladL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-10 10:31:12

He encontrado una buena alternativa! Funciona mejor para mí, sin poner el foco en otra cosa.

Intenta eso:

private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{    
    e.SuppressKeyPress = true;
}
 3
Author: kaspi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 22:14:43

Hice esto en mi control personalizado, hice esto enFocus ()

this.Parent.Focus();

Así que si texbox enfocado - al instante enfocar cuadro de texto padre (formulario, o panel...) Esta es una buena opción si desea hacer esto en el control personalizado.

 3
Author: Tommix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-30 12:54:54
    //using System;
    //using System.Collections.Generic;
    //using System.Linq;

    private void Form1_Load(object sender, EventArgs e)
    {
        FocusOnOtherControl(Controls.Cast<Control>(), button1);
    }

    private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
    {
        foreach (var control in controls)
        {
            if (control.GetType().Equals(typeof(TextBox)))
            {
                control.TabStop = false;
                control.LostFocus += new EventHandler((object sender, EventArgs e) =>
                {                     
                    focusOnMe.Focus();
                });
            }
        }
    }
 2
Author: Torus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-06 21:36:14

La forma en que lo evito es colocar todos mis controles winform. Hago todas las etiquetas y los controles winform no seleccionados como orden de tabulación 0, luego mi primer control como orden de tabulación 2 y luego incremento el orden de cada control seleccionable en 1, por lo que 3, 4, 5, etc...

De esta manera, cuando mis Winforms se inician, el primer cuadro de texto no tiene foco!

 1
Author: CosineCuber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-07 10:48:05

Puede hacer esto por dos métodos

  • simplemente haga que las propiedades" TabStop " del cuadro de texto deseado sean falsas ahora no se enfocará incluso si tiene un campo de texto
  • Arrastre dos cuadro de texto

    1. haga visible uno en el que no desea foucus que es textbox1
    2. haga que el segundo sea invisible y vaya a propiedades de ese campo de texto y seleccione

Tabindex valor a 0 de textbox2

  1. y seleccione el tabindex de su textbox1 a 1 ahora no se centrará en textbox1
 1
Author: Adiii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 06:36:44

Si todo lo que desea es el efecto óptico de que el cuadro de texto no tiene selección azul en todo su contenido, simplemente seleccione no text:

textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();

Después de esto, al agregar contenido con .Text += "...", no se mostrará ninguna selección azul.

 0
Author: Roland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-06 10:16:54

Por favor, intente establecer TabStop a False para su control de vista que no está enfocado.

Por ejemplo:

txtEmpID.TabStop = false;
 0
Author: Shaheer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-31 14:02:22

En el constructor del Formulario o UserControl que contiene el cuadro de texto escriba

SetStyle(ControlStyles.Selectable, false);

Después del componente de inicialización(); Fuente: https://stackoverflow.com/a/4811938/5750078

Ejemplo:

public partial class Main : UserControl
{

    public Main()
    {
        InitializeComponent();
        SetStyle(ControlStyles.Selectable, false);
    }
 -1
Author: Loaderon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-25 15:53:43